1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.596.2.12.2.22 2013/08/29 12:52:04 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 %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
395: my ($toprow,$bottomrow);
396: foreach my $foil (@$order) {
397: if ($grading{$foil} == 1) {
398: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
399: } else {
400: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
401: }
402: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
403: }
404: return '<blockquote><table border="1">'.
405: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
406: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
407: $bottomrow.'</tr></table></blockquote>';
408: } elsif ($response eq 'match') {
409: my %answer=&Apache::lonnet::str2hash($answer);
410: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
411: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
412: my ($toprow,$middlerow,$bottomrow);
413: foreach my $foil (@$order) {
414: my $item=shift(@items);
415: if ($grading{$foil} == 1) {
416: $toprow.='<td><b>'.$item.' </b></td>';
417: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
418: } else {
419: $toprow.='<td><i>'.$item.' </i></td>';
420: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
421: }
422: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
423: }
424: return '<blockquote><table border="1">'.
425: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
426: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
427: $middlerow.'</tr>'.
428: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
429: $bottomrow.'</tr></table></blockquote>';
430: } elsif ($response eq 'radiobutton') {
431: my %answer=&Apache::lonnet::str2hash($answer);
432: my ($toprow,$bottomrow);
433: my $correct =
434: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
435: foreach my $foil (@$order) {
436: if (exists($answer{$foil})) {
437: if ($foil eq $correct) {
438: $toprow.='<td><b>'.&mt('true').'</b></td>';
439: } else {
440: $toprow.='<td><i>'.&mt('true').'</i></td>';
441: }
442: } else {
443: $toprow.='<td>'.&mt('false').'</td>';
444: }
445: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
446: }
447: return '<blockquote><table border="1">'.
448: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
449: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
450: $bottomrow.'</tr></table></blockquote>';
451: } elsif ($response eq 'essay') {
452: if (! exists ($env{'form.'.$symb})) {
453: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
454: $env{'course.'.$env{'request.course.id'}.'.domain'},
455: $env{'course.'.$env{'request.course.id'}.'.num'});
456:
457: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
458: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
459: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
460: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
461: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
462: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
463: }
464: $answer =~ s-\n-<br />-g;
465: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
466: } elsif ( $response eq 'organic') {
467: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
468: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
469: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
470: return $result;
471: } elsif ( $response eq 'Task') {
472: if ( $answer eq 'SUBMITTED') {
473: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
474: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
475: return $result;
476: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
477: my @matches = grep(/^\Q$version\E.*?\.instance$/,
478: keys(%{$record}));
479: return join('<br />',($version,@matches));
480:
481:
482: } else {
483: my $result =
484: '<p>'
485: .&mt('Overall result: [_1]',
486: $record->{$version."resource.$respid.$partid.status"})
487: .'</p>';
488:
489: $result .= '<ul>';
490: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
491: keys(%{$record}));
492: foreach my $grade (sort(@grade)) {
493: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
494: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
495: $dim, $record->{$grade}).
496: '</li>';
497: }
498: $result.='</ul>';
499: return $result;
500: }
501: } elsif ( $response =~ m/(?:numerical|formula)/) {
502: $answer =
503: &Apache::loncommon::format_previous_attempt_value('submission',
504: $answer);
505: }
506: return $answer;
507: }
508:
509: #-- A couple of common js functions
510: sub commonJSfunctions {
511: my $request = shift;
512: $request->print(<<COMMONJSFUNCTIONS);
513: <script type="text/javascript" language="javascript">
514: function radioSelection(radioButton) {
515: var selection=null;
516: if (radioButton.length > 1) {
517: for (var i=0; i<radioButton.length; i++) {
518: if (radioButton[i].checked) {
519: return radioButton[i].value;
520: }
521: }
522: } else {
523: if (radioButton.checked) return radioButton.value;
524: }
525: return selection;
526: }
527:
528: function pullDownSelection(selectOne) {
529: var selection="";
530: if (selectOne.length > 1) {
531: for (var i=0; i<selectOne.length; i++) {
532: if (selectOne[i].selected) {
533: return selectOne[i].value;
534: }
535: }
536: } else {
537: // only one value it must be the selected one
538: return selectOne.value;
539: }
540: }
541: </script>
542: COMMONJSFUNCTIONS
543: }
544:
545: #--- Dumps the class list with usernames,list of sections,
546: #--- section, ids and fullnames for each user.
547: sub getclasslist {
548: my ($getsec,$filterlist,$getgroup) = @_;
549: my @getsec;
550: my @getgroup;
551: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
552: if (!ref($getsec)) {
553: if ($getsec ne '' && $getsec ne 'all') {
554: @getsec=($getsec);
555: }
556: } else {
557: @getsec=@{$getsec};
558: }
559: if (grep(/^all$/,@getsec)) { undef(@getsec); }
560: if (!ref($getgroup)) {
561: if ($getgroup ne '' && $getgroup ne 'all') {
562: @getgroup=($getgroup);
563: }
564: } else {
565: @getgroup=@{$getgroup};
566: }
567: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
568:
569: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
570: # Bail out if we were unable to get the classlist
571: return if (! defined($classlist));
572: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
573: #
574: my %sections;
575: my %fullnames;
576: foreach my $student (keys(%$classlist)) {
577: my $end =
578: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
579: my $start =
580: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
581: my $id =
582: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
583: my $section =
584: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
585: my $fullname =
586: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
587: my $status =
588: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
589: my $group =
590: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
591: # filter students according to status selected
592: if ($filterlist && (!($stu_status =~ /Any/))) {
593: if (!($stu_status =~ $status)) {
594: delete($classlist->{$student});
595: next;
596: }
597: }
598: # filter students according to groups selected
599: my @stu_groups = split(/,/,$group);
600: if (@getgroup) {
601: my $exclude = 1;
602: foreach my $grp (@getgroup) {
603: foreach my $stu_group (@stu_groups) {
604: if ($stu_group eq $grp) {
605: $exclude = 0;
606: }
607: }
608: if (($grp eq 'none') && !$group) {
609: $exclude = 0;
610: }
611: }
612: if ($exclude) {
613: delete($classlist->{$student});
614: }
615: }
616: $section = ($section ne '' ? $section : 'none');
617: if (&canview($section)) {
618: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
619: $sections{$section}++;
620: if ($classlist->{$student}) {
621: $fullnames{$student}=$fullname;
622: }
623: } else {
624: delete($classlist->{$student});
625: }
626: } else {
627: delete($classlist->{$student});
628: }
629: }
630: my %seen = ();
631: my @sections = sort(keys(%sections));
632: return ($classlist,\@sections,\%fullnames);
633: }
634:
635: sub canmodify {
636: my ($sec)=@_;
637: if ($perm{'mgr'}) {
638: if (!defined($perm{'mgr_section'})) {
639: # can modify whole class
640: return 1;
641: } else {
642: if ($sec eq $perm{'mgr_section'}) {
643: #can modify the requested section
644: return 1;
645: } else {
646: # can't modify the request section
647: return 0;
648: }
649: }
650: }
651: #can't modify
652: return 0;
653: }
654:
655: sub canview {
656: my ($sec)=@_;
657: if ($perm{'vgr'}) {
658: if (!defined($perm{'vgr_section'})) {
659: # can modify whole class
660: return 1;
661: } else {
662: if ($sec eq $perm{'vgr_section'}) {
663: #can modify the requested section
664: return 1;
665: } else {
666: # can't modify the request section
667: return 0;
668: }
669: }
670: }
671: #can't modify
672: return 0;
673: }
674:
675: #--- Retrieve the grade status of a student for all the parts
676: sub student_gradeStatus {
677: my ($symb,$udom,$uname,$partlist) = @_;
678: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
679: my %partstatus = ();
680: foreach (@$partlist) {
681: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
682: $status = 'nothing' if ($status eq '');
683: $partstatus{$_} = $status;
684: my $subkey = "resource.$_.submitted_by";
685: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
686: }
687: return %partstatus;
688: }
689:
690: # hidden form and javascript that calls the form
691: # Use by verifyscript and viewgrades
692: # Shows a student's view of problem and submission
693: sub jscriptNform {
694: my ($symb) = @_;
695: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
696: my $jscript='<script type="text/javascript" language="javascript">'."\n".
697: ' function viewOneStudent(user,domain) {'."\n".
698: ' document.onestudent.student.value = user;'."\n".
699: ' document.onestudent.userdom.value = domain;'."\n".
700: ' document.onestudent.submit();'."\n".
701: ' }'."\n".
702: '</script>'."\n";
703: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
704: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
705: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
706: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
707: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
708: '<input type="hidden" name="command" value="submission" />'."\n".
709: '<input type="hidden" name="student" value="" />'."\n".
710: '<input type="hidden" name="userdom" value="" />'."\n".
711: '</form>'."\n";
712: return $jscript;
713: }
714:
715:
716:
717: # Given the score (as a number [0-1] and the weight) what is the final
718: # point value? This function will round to the nearest tenth, third,
719: # or quarter if one of those is within the tolerance of .00001.
720: sub compute_points {
721: my ($score, $weight) = @_;
722:
723: my $tolerance = .00001;
724: my $points = $score * $weight;
725:
726: # Check for nearness to 1/x.
727: my $check_for_nearness = sub {
728: my ($factor) = @_;
729: my $num = ($points * $factor) + $tolerance;
730: my $floored_num = floor($num);
731: if ($num - $floored_num < 2 * $tolerance * $factor) {
732: return $floored_num / $factor;
733: }
734: return $points;
735: };
736:
737: $points = $check_for_nearness->(10);
738: $points = $check_for_nearness->(3);
739: $points = $check_for_nearness->(4);
740:
741: return $points;
742: }
743:
744: #------------------ End of general use routines --------------------
745:
746: #
747: # Find most similar essay
748: #
749:
750: sub most_similar {
751: my ($uname,$udom,$symb,$uessay)=@_;
752:
753: unless ($symb) { return ''; }
754:
755: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
756:
757: # ignore spaces and punctuation
758:
759: $uessay=~s/\W+/ /gs;
760:
761: # ignore empty submissions (occuring when only files are sent)
762:
763: unless ($uessay=~/\w+/s) { return ''; }
764:
765: # these will be returned. Do not care if not at least 50 percent similar
766: my $limit=0.6;
767: my $sname='';
768: my $sdom='';
769: my $scrsid='';
770: my $sessay='';
771: # go through all essays ...
772: foreach my $tkey (keys(%{$old_essays{$symb}})) {
773: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
774: # ... except the same student
775: next if (($tname eq $uname) && ($tdom eq $udom));
776: my $tessay=$old_essays{$symb}{$tkey};
777: $tessay=~s/\W+/ /gs;
778: # String similarity gives up if not even limit
779: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
780: # Found one
781: if ($tsimilar>$limit) {
782: $limit=$tsimilar;
783: $sname=$tname;
784: $sdom=$tdom;
785: $scrsid=$tcrsid;
786: $sessay=$old_essays{$symb}{$tkey};
787: }
788: }
789: if ($limit>0.6) {
790: return ($sname,$sdom,$scrsid,$sessay,$limit);
791: } else {
792: return ('','','','',0);
793: }
794: }
795:
796: #-------------------------------------------------------------------
797:
798: #------------------------------------ Receipt Verification Routines
799: #
800: #--- Check whether a receipt number is valid.---
801: sub verifyreceipt {
802: my $request = shift;
803:
804: my $courseid = $env{'request.course.id'};
805: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
806: $env{'form.receipt'};
807: $receipt =~ s/[^\-\d]//g;
808: my ($symb) = &get_symb($request);
809:
810: my $title.=
811: '<h3><span class="LC_info">'.
812: &mt('Verifying Receipt No. [_1]',$receipt).
813: '</span></h3>'."\n".
814: '<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
815: '</h4>'."\n";
816:
817: my ($string,$contents,$matches) = ('','',0);
818: my (undef,undef,$fullname) = &getclasslist('all','0');
819:
820: my $receiptparts=0;
821: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
822: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
823: my $parts=['0'];
824: if ($receiptparts) {
825: my $res_error;
826: ($parts)=&response_type($symb,\$res_error);
827: if ($res_error) {
828: return &navmap_errormsg();
829: }
830: }
831:
832: my $header =
833: &Apache::loncommon::start_data_table().
834: &Apache::loncommon::start_data_table_header_row().
835: '<th> '.&mt('Fullname').' </th>'."\n".
836: '<th> '.&mt('Username').' </th>'."\n".
837: '<th> '.&mt('Domain').' </th>';
838: if ($receiptparts) {
839: $header.='<th> '.&mt('Problem Part').' </th>';
840: }
841: $header.=
842: &Apache::loncommon::end_data_table_header_row();
843:
844: foreach (sort
845: {
846: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
847: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
848: }
849: return $a cmp $b;
850: } (keys(%$fullname))) {
851: my ($uname,$udom)=split(/\:/);
852: foreach my $part (@$parts) {
853: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
854: $contents.=
855: &Apache::loncommon::start_data_table_row().
856: '<td> '."\n".
857: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
858: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
859: '<td> '.$uname.' </td>'.
860: '<td> '.$udom.' </td>';
861: if ($receiptparts) {
862: $contents.='<td> '.$part.' </td>';
863: }
864: $contents.=
865: &Apache::loncommon::end_data_table_row()."\n";
866:
867: $matches++;
868: }
869: }
870: }
871: if ($matches == 0) {
872: $string = $title
873: .'<p class="LC_warning">'
874: .&mt('No match found for the above receipt number.')
875: .'</p>';
876: } else {
877: $string = &jscriptNform($symb).$title.
878: '<p>'.
879: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
880: '</p>'.
881: $header.
882: $contents.
883: &Apache::loncommon::end_data_table()."\n";
884: }
885: return $string.&show_grading_menu_form($symb);
886: }
887:
888: #--- This is called by a number of programs.
889: #--- Called from the Grading Menu - View/Grade an individual student
890: #--- Also called directly when one clicks on the subm button
891: # on the problem page.
892: sub listStudents {
893: my ($request) = shift;
894:
895: my ($symb) = &get_symb($request);
896: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
897: my $cnum = $env{"course.$env{'request.course.id'}.num"};
898: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
899: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
900: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
901: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
902: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
903: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
904:
905: my $result='<h3><span class="LC_info"> '
906: .&mt("$viewgrade Submissions for a Student or a Group of Students")
907: .'</span></h3>';
908:
909: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
910:
911: my %lt = &Apache::lonlocal::texthash (
912: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
913: 'single' => 'Please select the student before clicking on the Next button.',
914: );
915: $request->print(<<LISTJAVASCRIPT);
916: <script type="text/javascript" language="javascript">
917: function checkSelect(checkBox) {
918: var ctr=0;
919: var sense="";
920: if (checkBox.length > 1) {
921: for (var i=0; i<checkBox.length; i++) {
922: if (checkBox[i].checked) {
923: ctr++;
924: }
925: }
926: sense = '$lt{'multiple'}';
927: } else {
928: if (checkBox.checked) {
929: ctr = 1;
930: }
931: sense = '$lt{'single'}';
932: }
933: if (ctr == 0) {
934: alert(sense);
935: return false;
936: }
937: document.gradesub.submit();
938: }
939:
940: function reLoadList(formname) {
941: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
942: formname.command.value = 'submission';
943: formname.submit();
944: }
945: </script>
946: LISTJAVASCRIPT
947:
948: &commonJSfunctions($request);
949: $request->print($result);
950:
951: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
952: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
953: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
954: "\n".$table;
955:
956: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
957: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
958: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
959: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
960: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
961: .&Apache::lonhtmlcommon::row_closure();
962: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
963: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
964: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
965: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
966: .&Apache::lonhtmlcommon::row_closure();
967:
968: my $submission_options;
969: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
970: $submission_options.=
971: '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
972: }
973: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
974: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
975: $env{'form.Status'} = $saveStatus;
976: $submission_options.=
977: '<span class="LC_nobreak">'.
978: '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
979: &mt('last submission only').' </label></span>'."\n".
980: '<span class="LC_nobreak">'.
981: '<label><input type="radio" name="lastSub" value="last" /> '.
982: &mt('last submission & parts info').' </label></span>'."\n".
983: '<span class="LC_nobreak">'.
984: '<label><input type="radio" name="lastSub" value="datesub" /> '.
985: &mt('by dates and submissions').'</label></span>'."\n".
986: '<span class="LC_nobreak">'.
987: '<label><input type="radio" name="lastSub" value="all" /> '.
988: &mt('all details').'</label></span>';
989: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
990: .$submission_options
991: .&Apache::lonhtmlcommon::row_closure();
992:
993: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
994: .'<select name="increment">'
995: .'<option value="1">'.&mt('Whole Points').'</option>'
996: .'<option value=".5">'.&mt('Half Points').'</option>'
997: .'<option value=".25">'.&mt('Quarter Points').'</option>'
998: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
999: .'</select>'
1000: .&Apache::lonhtmlcommon::row_closure();
1001:
1002: $gradeTable .=
1003: &build_section_inputs().
1004: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
1005: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
1006: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
1007: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1008: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1009: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1010: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1011:
1012: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1013: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1014: } else {
1015: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1016: .&Apache::lonhtmlcommon::StatusOptions(
1017: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1018: .&Apache::lonhtmlcommon::row_closure();
1019: }
1020:
1021: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
1022: .'<input type="checkbox" name="checkPlag" checked="checked" />'
1023: .&Apache::lonhtmlcommon::row_closure(1)
1024: .&Apache::lonhtmlcommon::end_pick_box();
1025:
1026: $gradeTable .= '<p>'
1027: .&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"
1028: .'<input type="hidden" name="command" value="processGroup" />'
1029: .'</p>';
1030:
1031: # checkall buttons
1032: $gradeTable.=&check_script('gradesub', 'stuinfo');
1033: $gradeTable.='<input type="button" '."\n".
1034: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1035: 'value="'.&mt('Next').' →" /> <br />'."\n";
1036: $gradeTable.=&check_buttons();
1037: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1038: $gradeTable.= &Apache::loncommon::start_data_table().
1039: &Apache::loncommon::start_data_table_header_row();
1040: my $loop = 0;
1041: while ($loop < 2) {
1042: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
1043: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
1044: if ($env{'form.showgrading'} eq 'yes'
1045: && $submitonly ne 'queued'
1046: && $submitonly ne 'all') {
1047: foreach my $part (sort(@$partlist)) {
1048: my $display_part=
1049: &get_display_part((split(/_/,$part))[0],$symb);
1050: $gradeTable.=
1051: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1052: }
1053: } elsif ($submitonly eq 'queued') {
1054: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
1055: }
1056: $loop++;
1057: # $gradeTable.='<td></td>' if ($loop%2 ==1);
1058: }
1059: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1060:
1061: my $ctr = 0;
1062: foreach my $student (sort
1063: {
1064: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
1065: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
1066: }
1067: return $a cmp $b;
1068: }
1069: (keys(%$fullname))) {
1070: my ($uname,$udom) = split(/:/,$student);
1071:
1072: my %status = ();
1073:
1074: if ($submitonly eq 'queued') {
1075: my %queue_status =
1076: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1077: $udom,$uname);
1078: next if (!defined($queue_status{'gradingqueue'}));
1079: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1080: }
1081:
1082: if ($env{'form.showgrading'} eq 'yes'
1083: && $submitonly ne 'queued'
1084: && $submitonly ne 'all') {
1085: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1086: my $submitted = 0;
1087: my $graded = 0;
1088: my $incorrect = 0;
1089: foreach (keys(%status)) {
1090: $submitted = 1 if ($status{$_} ne 'nothing');
1091: $graded = 1 if ($status{$_} =~ /^ungraded/);
1092: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1093:
1094: my ($foo,$partid,$foo1) = split(/\./,$_);
1095: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1096: $submitted = 0;
1097: my ($part)=split(/\./,$partid);
1098: $gradeTable.='<input type="hidden" name="'.
1099: $student.':'.$part.':submitted_by" value="'.
1100: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1101: }
1102: }
1103:
1104: next if (!$submitted && ($submitonly eq 'yes' ||
1105: $submitonly eq 'incorrect' ||
1106: $submitonly eq 'graded'));
1107: next if (!$graded && ($submitonly eq 'graded'));
1108: next if (!$incorrect && $submitonly eq 'incorrect');
1109: }
1110:
1111: $ctr++;
1112: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1113: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1114: if ( $perm{'vgr'} eq 'F' ) {
1115: if ($ctr%2 ==1) {
1116: $gradeTable.= &Apache::loncommon::start_data_table_row();
1117: }
1118: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1119: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1120: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1121: ') " /> </label></td>'."\n".'<td>'.
1122: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1123: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1124:
1125: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1126: foreach (sort(keys(%status))) {
1127: next if ($_ =~ /^resource.*?submitted_by$/);
1128: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1129: }
1130: }
1131: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1132: if ($ctr%2 ==0) {
1133: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1134: }
1135: }
1136: }
1137: if ($ctr%2 ==1) {
1138: $gradeTable.='<td> </td><td> </td><td> </td>';
1139: if ($env{'form.showgrading'} eq 'yes'
1140: && $submitonly ne 'queued'
1141: && $submitonly ne 'all') {
1142: foreach (@$partlist) {
1143: $gradeTable.='<td> </td>';
1144: }
1145: } elsif ($submitonly eq 'queued') {
1146: $gradeTable.='<td> </td>';
1147: }
1148: $gradeTable.=&Apache::loncommon::end_data_table_row();
1149: }
1150:
1151: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1152: '<input type="button" '.
1153: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1154: 'value="'.&mt('Next').' →" /></form>'."\n";
1155: if ($ctr == 0) {
1156: my $num_students=(scalar(keys(%$fullname)));
1157: if ($num_students eq 0) {
1158: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1159: } else {
1160: my $submissions='submissions';
1161: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1162: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1163: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1164: $gradeTable='<br /> <span class="LC_warning">'.
1165: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1166: $num_students).
1167: '</span><br />';
1168: }
1169: } elsif ($ctr == 1) {
1170: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1171: }
1172: $gradeTable.=&show_grading_menu_form($symb);
1173: $request->print($gradeTable);
1174: return '';
1175: }
1176:
1177: #---- Called from the listStudents routine
1178:
1179: sub check_script {
1180: my ($form, $type)=@_;
1181: my $chkallscript='<script type="text/javascript">
1182: function checkall() {
1183: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1184: ele = document.forms.'.$form.'.elements[i];
1185: if (ele.name == "'.$type.'") {
1186: document.forms.'.$form.'.elements[i].checked=true;
1187: }
1188: }
1189: }
1190:
1191: function checksec() {
1192: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1193: ele = document.forms.'.$form.'.elements[i];
1194: string = document.forms.'.$form.'.chksec.value;
1195: if
1196: (ele.value.indexOf(":::SECTION"+string)>0) {
1197: document.forms.'.$form.'.elements[i].checked=true;
1198: }
1199: }
1200: }
1201:
1202:
1203: function uncheckall() {
1204: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1205: ele = document.forms.'.$form.'.elements[i];
1206: if (ele.name == "'.$type.'") {
1207: document.forms.'.$form.'.elements[i].checked=false;
1208: }
1209: }
1210: }
1211:
1212: </script>'."\n";
1213: return $chkallscript;
1214: }
1215:
1216: sub check_buttons {
1217: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1218: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1219: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1220: $buttons.='<input type="text" size="5" name="chksec" /> ';
1221: return $buttons;
1222: }
1223:
1224: # Displays the submissions for one student or a group of students
1225: sub processGroup {
1226: my ($request) = shift;
1227: my $ctr = 0;
1228: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1229: my $total = scalar(@stuchecked)-1;
1230:
1231: foreach my $student (@stuchecked) {
1232: my ($uname,$udom,$fullname) = split(/:/,$student);
1233: $env{'form.student'} = $uname;
1234: $env{'form.userdom'} = $udom;
1235: $env{'form.fullname'} = $fullname;
1236: &submission($request,$ctr,$total);
1237: $ctr++;
1238: }
1239: return '';
1240: }
1241:
1242: #------------------------------------------------------------------------------------
1243: #
1244: #-------------------------- Next few routines handles grading by student, essentially
1245: # handles essay response type problem/part
1246: #
1247: #--- Javascript to handle the submission page functionality ---
1248: sub sub_page_js {
1249: my $request = shift;
1250: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1251: $request->print(<<SUBJAVASCRIPT);
1252: <script type="text/javascript" language="javascript">
1253: function updateRadio(formname,id,weight) {
1254: var gradeBox = formname["GD_BOX"+id];
1255: var radioButton = formname["RADVAL"+id];
1256: var oldpts = formname["oldpts"+id].value;
1257: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1258: gradeBox.value = pts;
1259: var resetbox = false;
1260: if (isNaN(pts) || pts < 0) {
1261: alert("$alertmsg"+pts);
1262: for (var i=0; i<radioButton.length; i++) {
1263: if (radioButton[i].checked) {
1264: gradeBox.value = i;
1265: resetbox = true;
1266: }
1267: }
1268: if (!resetbox) {
1269: formtextbox.value = "";
1270: }
1271: return;
1272: }
1273:
1274: if (pts > weight) {
1275: var resp = confirm("You entered a value ("+pts+
1276: ") greater than the weight for the part. Accept?");
1277: if (resp == false) {
1278: gradeBox.value = oldpts;
1279: return;
1280: }
1281: }
1282:
1283: for (var i=0; i<radioButton.length; i++) {
1284: radioButton[i].checked=false;
1285: if (pts == i && pts != "") {
1286: radioButton[i].checked=true;
1287: }
1288: }
1289: updateSelect(formname,id);
1290: formname["stores"+id].value = "0";
1291: }
1292:
1293: function writeBox(formname,id,pts) {
1294: var gradeBox = formname["GD_BOX"+id];
1295: if (checkSolved(formname,id) == 'update') {
1296: gradeBox.value = pts;
1297: } else {
1298: var oldpts = formname["oldpts"+id].value;
1299: gradeBox.value = oldpts;
1300: var radioButton = formname["RADVAL"+id];
1301: for (var i=0; i<radioButton.length; i++) {
1302: radioButton[i].checked=false;
1303: if (i == oldpts) {
1304: radioButton[i].checked=true;
1305: }
1306: }
1307: }
1308: formname["stores"+id].value = "0";
1309: updateSelect(formname,id);
1310: return;
1311: }
1312:
1313: function clearRadBox(formname,id) {
1314: if (checkSolved(formname,id) == 'noupdate') {
1315: updateSelect(formname,id);
1316: return;
1317: }
1318: gradeSelect = formname["GD_SEL"+id];
1319: for (var i=0; i<gradeSelect.length; i++) {
1320: if (gradeSelect[i].selected) {
1321: var selectx=i;
1322: }
1323: }
1324: var stores = formname["stores"+id];
1325: if (selectx == stores.value) { return };
1326: var gradeBox = formname["GD_BOX"+id];
1327: gradeBox.value = "";
1328: var radioButton = formname["RADVAL"+id];
1329: for (var i=0; i<radioButton.length; i++) {
1330: radioButton[i].checked=false;
1331: }
1332: stores.value = selectx;
1333: }
1334:
1335: function checkSolved(formname,id) {
1336: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1337: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1338: if (!reply) {return "noupdate";}
1339: formname.overRideScore.value = 'yes';
1340: }
1341: return "update";
1342: }
1343:
1344: function updateSelect(formname,id) {
1345: formname["GD_SEL"+id][0].selected = true;
1346: return;
1347: }
1348:
1349: //=========== Check that a point is assigned for all the parts ============
1350: function checksubmit(formname,val,total,parttot) {
1351: formname.gradeOpt.value = val;
1352: if (val == "Save & Next") {
1353: for (i=0;i<=total;i++) {
1354: for (j=0;j<parttot;j++) {
1355: var partid = formname["partid"+i+"_"+j].value;
1356: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1357: var points = formname["GD_BOX"+i+"_"+partid].value;
1358: if (points == "") {
1359: var name = formname["name"+i].value;
1360: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1361: var resp = confirm("You did not assign a score for "+studentID+
1362: ", part "+partid+". Continue?");
1363: if (resp == false) {
1364: formname["GD_BOX"+i+"_"+partid].focus();
1365: return false;
1366: }
1367: }
1368: }
1369:
1370: }
1371: }
1372:
1373: }
1374: if (val == "Grade Student") {
1375: formname.showgrading.value = "yes";
1376: if (formname.Status.value == "") {
1377: formname.Status.value = "Active";
1378: }
1379: formname.studentNo.value = total;
1380: }
1381: formname.submit();
1382: }
1383:
1384: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1385: function checkSubmitPage(formname,total) {
1386: noscore = new Array(100);
1387: var ptr = 0;
1388: for (i=1;i<total;i++) {
1389: var partid = formname["q_"+i].value;
1390: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1391: var points = formname["GD_BOX"+i+"_"+partid].value;
1392: var status = formname["solved"+i+"_"+partid].value;
1393: if (points == "" && status != "correct_by_student") {
1394: noscore[ptr] = i;
1395: ptr++;
1396: }
1397: }
1398: }
1399: if (ptr != 0) {
1400: var sense = ptr == 1 ? ": " : "s: ";
1401: var prolist = "";
1402: if (ptr == 1) {
1403: prolist = noscore[0];
1404: } else {
1405: var i = 0;
1406: while (i < ptr-1) {
1407: prolist += noscore[i]+", ";
1408: i++;
1409: }
1410: prolist += "and "+noscore[i];
1411: }
1412: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1413: if (resp == false) {
1414: return false;
1415: }
1416: }
1417:
1418: formname.submit();
1419: }
1420: </script>
1421: SUBJAVASCRIPT
1422: }
1423:
1424: #--- javascript for essay type problem --
1425: sub sub_page_kw_js {
1426: my $request = shift;
1427: my $iconpath = $request->dir_config('lonIconsURL');
1428: &commonJSfunctions($request);
1429:
1430: my $inner_js_msg_central=<<INNERJS;
1431: <script text="text/javascript">
1432: function checkInput() {
1433: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1434: var nmsg = opener.document.SCORE.savemsgN.value;
1435: var usrctr = document.msgcenter.usrctr.value;
1436: var newval = opener.document.SCORE["newmsg"+usrctr];
1437: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1438:
1439: var msgchk = "";
1440: if (document.msgcenter.subchk.checked) {
1441: msgchk = "msgsub,";
1442: }
1443: var includemsg = 0;
1444: for (var i=1; i<=nmsg; i++) {
1445: var opnmsg = opener.document.SCORE["savemsg"+i];
1446: var frmmsg = document.msgcenter["msg"+i];
1447: opnmsg.value = opener.checkEntities(frmmsg.value);
1448: var showflg = opener.document.SCORE["shownOnce"+i];
1449: showflg.value = "1";
1450: var chkbox = document.msgcenter["msgn"+i];
1451: if (chkbox.checked) {
1452: msgchk += "savemsg"+i+",";
1453: includemsg = 1;
1454: }
1455: }
1456: if (document.msgcenter.newmsgchk.checked) {
1457: msgchk += "newmsg"+usrctr;
1458: includemsg = 1;
1459: }
1460: imgformname = opener.document.SCORE["mailicon"+usrctr];
1461: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1462: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1463: includemsg.value = msgchk;
1464:
1465: self.close()
1466:
1467: }
1468: </script>
1469: INNERJS
1470:
1471: my $inner_js_highlight_central=<<INNERJS;
1472: <script type="text/javascript">
1473: function updateChoice(flag) {
1474: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1475: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1476: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1477: opener.document.SCORE.refresh.value = "on";
1478: if (opener.document.SCORE.keywords.value!=""){
1479: opener.document.SCORE.submit();
1480: }
1481: self.close()
1482: }
1483: </script>
1484: INNERJS
1485:
1486: my $start_page_msg_central =
1487: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1488: {'js_ready' => 1,
1489: 'only_body' => 1,
1490: 'bgcolor' =>'#FFFFFF',});
1491: my $end_page_msg_central =
1492: &Apache::loncommon::end_page({'js_ready' => 1});
1493:
1494:
1495: my $start_page_highlight_central =
1496: &Apache::loncommon::start_page('Highlight Central',
1497: $inner_js_highlight_central,
1498: {'js_ready' => 1,
1499: 'only_body' => 1,
1500: 'bgcolor' =>'#FFFFFF',});
1501: my $end_page_highlight_central =
1502: &Apache::loncommon::end_page({'js_ready' => 1});
1503:
1504: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1505: $docopen=~s/^document\.//;
1506: my %lt = &Apache::lonlocal::texthash(
1507: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1508: plse => 'Please select a word or group of words from document and then click this link.',
1509: adds => 'Add selection to keyword list? Edit if desired.',
1510: comp => 'Compose Message for: ',
1511: incl => 'Include',
1512: type => 'Type',
1513: subj => 'Subject',
1514: mesa => 'Message',
1515: new => 'New',
1516: save => 'Save',
1517: canc => 'Cancel',
1518: kehi => 'Keyword Highlight Options',
1519: txtc => 'Text Color',
1520: font => 'Font Size',
1521: fnst => 'Font Style',
1522: );
1523: $request->print(<<SUBJAVASCRIPT);
1524: <script type="text/javascript" language="javascript">
1525:
1526: //===================== Show list of keywords ====================
1527: function keywords(formname) {
1528: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1529: if (nret==null) return;
1530: formname.keywords.value = nret;
1531:
1532: if (formname.keywords.value != "") {
1533: formname.refresh.value = "on";
1534: formname.submit();
1535: }
1536: return;
1537: }
1538:
1539: //===================== Script to view submitted by ==================
1540: function viewSubmitter(submitter) {
1541: document.SCORE.refresh.value = "on";
1542: document.SCORE.NCT.value = "1";
1543: document.SCORE.unamedom0.value = submitter;
1544: document.SCORE.submit();
1545: return;
1546: }
1547:
1548: //===================== Script to add keyword(s) ==================
1549: function getSel() {
1550: if (document.getSelection) txt = document.getSelection();
1551: else if (document.selection) txt = document.selection.createRange().text;
1552: else return;
1553: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1554: if (cleantxt=="") {
1555: alert("$lt{'plse'}");
1556: return;
1557: }
1558: var nret = prompt("$lt{'adds'}",cleantxt);
1559: if (nret==null) return;
1560: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1561: if (document.SCORE.keywords.value != "") {
1562: document.SCORE.refresh.value = "on";
1563: document.SCORE.submit();
1564: }
1565: return;
1566: }
1567:
1568: //====================== Script for composing message ==============
1569: // preload images
1570: img1 = new Image();
1571: img1.src = "$iconpath/mailbkgrd.gif";
1572: img2 = new Image();
1573: img2.src = "$iconpath/mailto.gif";
1574:
1575: function msgCenter(msgform,usrctr,fullname) {
1576: var Nmsg = msgform.savemsgN.value;
1577: savedMsgHeader(Nmsg,usrctr,fullname);
1578: var subject = msgform.msgsub.value;
1579: var msgchk = document.SCORE["includemsg"+usrctr].value;
1580: re = /msgsub/;
1581: var shwsel = "";
1582: if (re.test(msgchk)) { shwsel = "checked" }
1583: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1584: displaySubject(checkEntities(subject),shwsel);
1585: for (var i=1; i<=Nmsg; i++) {
1586: var testmsg = "savemsg"+i+",";
1587: re = new RegExp(testmsg,"g");
1588: shwsel = "";
1589: if (re.test(msgchk)) { shwsel = "checked" }
1590: var message = document.SCORE["savemsg"+i].value;
1591: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1592: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1593: //any < is already converted to <, etc. However, only once!!
1594: }
1595: newmsg = document.SCORE["newmsg"+usrctr].value;
1596: shwsel = "";
1597: re = /newmsg/;
1598: if (re.test(msgchk)) { shwsel = "checked" }
1599: newMsg(newmsg,shwsel);
1600: msgTail();
1601: return;
1602: }
1603:
1604: function checkEntities(strx) {
1605: if (strx.length == 0) return strx;
1606: var orgStr = ["&", "<", ">", '"'];
1607: var newStr = ["&", "<", ">", """];
1608: var counter = 0;
1609: while (counter < 4) {
1610: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1611: counter++;
1612: }
1613: return strx;
1614: }
1615:
1616: function strReplace(strx, orgStr, newStr) {
1617: return strx.split(orgStr).join(newStr);
1618: }
1619:
1620: function savedMsgHeader(Nmsg,usrctr,fullname) {
1621: var height = 70*Nmsg+250;
1622: if (height > 600) {
1623: height = 600;
1624: }
1625: var xpos = (screen.width-600)/2;
1626: xpos = (xpos < 0) ? '0' : xpos;
1627: var ypos = (screen.height-height)/2-30;
1628: ypos = (ypos < 0) ? '0' : ypos;
1629:
1630: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1631: pWin.focus();
1632: pDoc = pWin.document;
1633: pDoc.$docopen;
1634: pDoc.write('$start_page_msg_central');
1635:
1636: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1637: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1638: pDoc.write("<h3><span class=\\"LC_info\\"> $lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1639:
1640: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1641: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1642: pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1643: }
1644: function displaySubject(msg,shwsel) {
1645: pDoc = pWin.document;
1646: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1647: pDoc.write("<td>$lt{'subj'}<\\/td>");
1648: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1649: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1650: }
1651:
1652: function displaySavedMsg(ctr,msg,shwsel) {
1653: pDoc = pWin.document;
1654: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1655: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1656: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1657: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1658: }
1659:
1660: function newMsg(newmsg,shwsel) {
1661: pDoc = pWin.document;
1662: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1663: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1664: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1665: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1666: }
1667:
1668: function msgTail() {
1669: pDoc = pWin.document;
1670: pDoc.write("<\\/table>");
1671: pDoc.write("<\\/td><\\/tr><\\/table> ");
1672: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1673: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1674: pDoc.write("<\\/form>");
1675: pDoc.write('$end_page_msg_central');
1676: pDoc.close();
1677: }
1678:
1679: //====================== Script for keyword highlight options ==============
1680: function kwhighlight() {
1681: var kwclr = document.SCORE.kwclr.value;
1682: var kwsize = document.SCORE.kwsize.value;
1683: var kwstyle = document.SCORE.kwstyle.value;
1684: var redsel = "";
1685: var grnsel = "";
1686: var blusel = "";
1687: if (kwclr=="red") {var redsel="checked"};
1688: if (kwclr=="green") {var grnsel="checked"};
1689: if (kwclr=="blue") {var blusel="checked"};
1690: var sznsel = "";
1691: var sz1sel = "";
1692: var sz2sel = "";
1693: if (kwsize=="0") {var sznsel="checked"};
1694: if (kwsize=="+1") {var sz1sel="checked"};
1695: if (kwsize=="+2") {var sz2sel="checked"};
1696: var synsel = "";
1697: var syisel = "";
1698: var sybsel = "";
1699: if (kwstyle=="") {var synsel="checked"};
1700: if (kwstyle=="<i>") {var syisel="checked"};
1701: if (kwstyle=="<b>") {var sybsel="checked"};
1702: highlightCentral();
1703: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1704: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1705: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1706: highlightend();
1707: return;
1708: }
1709:
1710: function highlightCentral() {
1711: // if (window.hwdWin) window.hwdWin.close();
1712: var xpos = (screen.width-400)/2;
1713: xpos = (xpos < 0) ? '0' : xpos;
1714: var ypos = (screen.height-330)/2-30;
1715: ypos = (ypos < 0) ? '0' : ypos;
1716:
1717: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1718: hwdWin.focus();
1719: var hDoc = hwdWin.document;
1720: hDoc.$docopen;
1721: hDoc.write('$start_page_highlight_central');
1722: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1723: hDoc.write("<h3><span class=\\"LC_info\\"> $lt{'kehi'}<\\/span><\\/h3><br /><br />");
1724:
1725: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1726: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1727: hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1728: }
1729:
1730: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1731: var hDoc = hwdWin.document;
1732: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1733: hDoc.write("<td align=\\"left\\">");
1734: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1735: hDoc.write("<td align=\\"left\\">");
1736: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1737: hDoc.write("<td align=\\"left\\">");
1738: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1739: hDoc.write("<\\/tr>");
1740: }
1741:
1742: function highlightend() {
1743: var hDoc = hwdWin.document;
1744: hDoc.write("<\\/table>");
1745: hDoc.write("<\\/td><\\/tr><\\/table> ");
1746: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1747: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1748: hDoc.write("<\\/form>");
1749: hDoc.write('$end_page_highlight_central');
1750: hDoc.close();
1751: }
1752:
1753: </script>
1754: SUBJAVASCRIPT
1755: }
1756:
1757: sub get_increment {
1758: my $increment = $env{'form.increment'};
1759: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1760: $increment != .1) {
1761: $increment = 1;
1762: }
1763: return $increment;
1764: }
1765:
1766: sub gradeBox_start {
1767: return (
1768: &Apache::loncommon::start_data_table()
1769: .&Apache::loncommon::start_data_table_header_row()
1770: .'<th>'.&mt('Part').'</th>'
1771: .'<th>'.&mt('Points').'</th>'
1772: .'<th> </th>'
1773: .'<th>'.&mt('Assign Grade').'</th>'
1774: .'<th>'.&mt('Weight').'</th>'
1775: .'<th>'.&mt('Grade Status').'</th>'
1776: .&Apache::loncommon::end_data_table_header_row()
1777: );
1778: }
1779:
1780: sub gradeBox_end {
1781: return (
1782: &Apache::loncommon::end_data_table()
1783: );
1784: }
1785: #--- displays the grading box, used in essay type problem and grading by page/sequence
1786: sub gradeBox {
1787: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1788: my $checkIcon = '<img alt="'.&mt('Check Mark').
1789: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1790: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1791: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1792: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1793: $wgt = ($wgt > 0 ? $wgt : '1');
1794: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1795: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1796: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1797: my $display_part= &get_display_part($partid,$symb);
1798: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1799: [$partid]);
1800: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1801: if ($last_resets{$partid}) {
1802: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1803: }
1804: my $result=&Apache::loncommon::start_data_table_row();
1805: my $ctr = 0;
1806: my $thisweight = 0;
1807: my $increment = &get_increment();
1808:
1809: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1810: while ($thisweight<=$wgt) {
1811: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1812: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1813: $thisweight.')" value="'.$thisweight.'" '.
1814: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1815: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1816: $thisweight += $increment;
1817: $ctr++;
1818: }
1819: $radio.='</tr></table>';
1820:
1821: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1822: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1823: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1824: $wgt.')" /></td>'."\n";
1825: $line.='<td>/'.$wgt.' '.$wgtmsg.
1826: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1827: ' </td>'."\n";
1828: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1829: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1830: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1831: $line.='<option></option>'.
1832: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1833: } else {
1834: $line.='<option selected="selected"></option>'.
1835: '<option value="excused" >'.&mt('excused').'</option>';
1836: }
1837: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1838:
1839:
1840: $result .=
1841: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1842: $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1843: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1844: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1845: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1846: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1847: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1848: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1849: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1850: $aggtries.'" />'."\n";
1851: my $res_error;
1852: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1853: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1854: if ($res_error) {
1855: return &navmap_errormsg();
1856: }
1857: return $result;
1858: }
1859:
1860: sub handback_box {
1861: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
1862: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1863: my (@respids);
1864: my @part_response_id = &flatten_responseType($responseType);
1865: foreach my $part_response_id (@part_response_id) {
1866: my ($part,$resp) = @{ $part_response_id };
1867: if ($part eq $partid) {
1868: push(@respids,$resp);
1869: }
1870: }
1871: my $result;
1872: foreach my $respid (@respids) {
1873: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1874: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1875: next if (!@$files);
1876: my $file_counter = 0;
1877: foreach my $file (@$files) {
1878: if ($file =~ /\/portfolio\//) {
1879: $file_counter++;
1880: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1881: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1882: $file_disp = "$name.$ext";
1883: $file = $file_path.$file_disp;
1884: $result.=&mt('Return commented version of [_1] to student.',
1885: '<span class="LC_filename">'.$file_disp.'</span>');
1886: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1887: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1888: }
1889: }
1890: if ($file_counter) {
1891: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1892: '<span class="LC_info">'.
1893: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1894: }
1895: }
1896: return $result;
1897: }
1898:
1899: sub show_problem {
1900: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1901: my $rendered;
1902: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1903: &Apache::lonxml::remember_problem_counter();
1904: if ($mode eq 'both' or $mode eq 'text') {
1905: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1906: $env{'request.course.id'},
1907: undef,\%form);
1908: }
1909: if ($removeform) {
1910: $rendered=~s|<form(.*?)>||g;
1911: $rendered=~s|</form>||g;
1912: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1913: }
1914: my $companswer;
1915: if ($mode eq 'both' or $mode eq 'answer') {
1916: &Apache::lonxml::restore_problem_counter();
1917: $companswer=
1918: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1919: $env{'request.course.id'},
1920: %form);
1921: }
1922: if ($removeform) {
1923: $companswer=~s|<form(.*?)>||g;
1924: $companswer=~s|</form>||g;
1925: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1926: }
1927: my $renderheading = &mt('View of the problem');
1928: my $answerheading = &mt('Correct answer');
1929: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1930: my $stu_fullname = $env{'form.fullname'};
1931: if ($stu_fullname eq '') {
1932: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1933: }
1934: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1935: if ($forwhom ne '') {
1936: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1937: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1938: }
1939: }
1940: $rendered=
1941: '<div class="LC_Box">'
1942: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1943: .$rendered
1944: .'</div>';
1945: $companswer=
1946: '<div class="LC_Box">'
1947: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1948: .$companswer
1949: .'</div>';
1950: my $result;
1951: if ($mode eq 'both') {
1952: $result=$rendered.$companswer;
1953: } elsif ($mode eq 'text') {
1954: $result=$rendered;
1955: } elsif ($mode eq 'answer') {
1956: $result=$companswer;
1957: }
1958: return $result;
1959: }
1960:
1961: sub files_exist {
1962: my ($r, $symb) = @_;
1963: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1964:
1965: foreach my $student (@students) {
1966: my ($uname,$udom,$fullname) = split(/:/,$student);
1967: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1968: $udom,$uname);
1969: my ($string,$timestamp)= &get_last_submission(\%record);
1970: foreach my $submission (@$string) {
1971: my ($partid,$respid) =
1972: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1973: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1974: \%record);
1975: return 1 if (@$files);
1976: }
1977: }
1978: return 0;
1979: }
1980:
1981: sub download_all_link {
1982: my ($r,$symb) = @_;
1983: my $all_students =
1984: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1985:
1986: my $parts =
1987: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1988:
1989: my $identifier = &Apache::loncommon::get_cgi_id();
1990: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1991: 'cgi.'.$identifier.'.symb' => $symb,
1992: 'cgi.'.$identifier.'.parts' => $parts,});
1993: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1994: &mt('Download All Submitted Documents').'</a>');
1995: return
1996: }
1997:
1998: sub build_section_inputs {
1999: my $section_inputs;
2000: if ($env{'form.section'} eq '') {
2001: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
2002: } else {
2003: my @sections = &Apache::loncommon::get_env_multiple('form.section');
2004: foreach my $section (@sections) {
2005: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
2006: }
2007: }
2008: return $section_inputs;
2009: }
2010:
2011: # --------------------------- show submissions of a student, option to grade
2012: sub submission {
2013: my ($request,$counter,$total) = @_;
2014: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2015: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
2016: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2017: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
2018: my ($symb) = &get_symb($request);
2019: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
2020:
2021: if (!&canview($usec)) {
2022: $request->print('<span class="LC_warning">Unable to view requested student.('.
2023: $uname.':'.$udom.' in section '.$usec.' in course id '.
2024: $env{'request.course.id'}.')</span>');
2025: $request->print(&show_grading_menu_form($symb));
2026: return;
2027: }
2028:
2029: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
2030: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
2031: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
2032: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
2033: my $checkIcon = '<img alt="'.&mt('Check Mark').
2034: '" src="'.$request->dir_config('lonIconsURL').
2035: '/check.gif" height="16" border="0" />';
2036:
2037: # header info
2038: if ($counter == 0) {
2039: &sub_page_js($request);
2040: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
2041: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
2042: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
2043: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
2044: &download_all_link($request, $symb);
2045: }
2046: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
2047: '<h4> '.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
2048:
2049: # option to display problem, only once else it cause problems
2050: # with the form later since the problem has a form.
2051: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
2052: my $mode;
2053: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
2054: $mode='both';
2055: } elsif ($env{'form.vProb'} eq 'yes') {
2056: $mode='text';
2057: } elsif ($env{'form.vAns'} eq 'yes') {
2058: $mode='answer';
2059: }
2060: &Apache::lonxml::clear_problem_counter();
2061: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
2062: }
2063:
2064: # kwclr is the only variable that is guaranteed not to be blank
2065: # if this subroutine has been called once.
2066: my %keyhash = ();
2067: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
2068: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
2069: $env{'course.'.$env{'request.course.id'}.'.domain'},
2070: $env{'course.'.$env{'request.course.id'}.'.num'});
2071:
2072: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2073: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
2074: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
2075: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
2076: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
2077: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
2078: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
2079: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2080: }
2081: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2082: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2083: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2084: '<input type="hidden" name="command" value="handgrade" />'."\n".
2085: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
2086: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2087: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2088: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
2089: '<input type="hidden" name="refresh" value="off" />'."\n".
2090: '<input type="hidden" name="studentNo" value="" />'."\n".
2091: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2092: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2093: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
2094: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2095: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2096: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2097: &build_section_inputs().
2098: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2099: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
2100: '<input type="hidden" name="NCT"'.
2101: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2102: if ($env{'form.handgrade'} eq 'yes') {
2103: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2104: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2105: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2106: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2107: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2108: '<input type="hidden" name="shownSub" value="0" />'."\n".
2109: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2110: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2111: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2112: }
2113: }
2114:
2115: my ($cts,$prnmsg) = (1,'');
2116: while ($cts <= $env{'form.savemsgN'}) {
2117: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2118: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2119: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2120: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2121: '" />'."\n".
2122: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2123: $cts++;
2124: }
2125: $request->print($prnmsg);
2126:
2127: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
2128:
2129: my %lt = &Apache::lonlocal::texthash(
2130: keyw => 'Keyword Options',
2131: list => 'List',
2132: past => 'Paste Selection to List',
2133: high => 'Highlight Attribute',
2134: );
2135: #
2136: # Print out the keyword options line
2137: #
2138: $request->print(<<KEYWORDS);
2139: <b>$lt{'keyw'}:</b>
2140: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>
2141: <a href="#" onmousedown="javascript:getSel(); return false"
2142: class="page">$lt{'past'}</a>
2143: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
2144: KEYWORDS
2145: #
2146: # Load the other essays for similarity check
2147: #
2148: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2149: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2150: $apath=&escape($apath);
2151: $apath=~s/\W/\_/gs;
2152: &init_old_essays($symb,$apath,$adom,$aname);
2153: }
2154: }
2155:
2156: # This is where output for one specific student would start
2157: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2158: $request->print(
2159: "\n\n"
2160: .'<div class="LC_grade_show_user'.$add_class.'">'
2161: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2162: ."\n"
2163: );
2164:
2165: # Show additional functions if allowed
2166: if ($perm{'vgr'}) {
2167: $request->print(
2168: &Apache::loncommon::track_student_link(
2169: &mt('View recent activity'),
2170: $uname,$udom,'check')
2171: .' '
2172: );
2173: }
2174: if ($perm{'opa'}) {
2175: $request->print(
2176: &Apache::loncommon::pprmlink(
2177: &mt('Set/Change parameters'),
2178: $uname,$udom,$symb,'check'));
2179: }
2180:
2181: # Show Problem
2182: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2183: my $mode;
2184: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2185: $mode='both';
2186: } elsif ($env{'form.vProb'} eq 'all' ) {
2187: $mode='text';
2188: } elsif ($env{'form.vAns'} eq 'all') {
2189: $mode='answer';
2190: }
2191: &Apache::lonxml::clear_problem_counter();
2192: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2193: }
2194:
2195: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2196: my $res_error;
2197: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2198: if ($res_error) {
2199: $request->print(&navmap_errormsg());
2200: return;
2201: }
2202:
2203: # Display student info
2204: $request->print(($counter == 0 ? '' : '<br />'));
2205:
2206: my $result='<div class="LC_Box">'
2207: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2208: $result.='<input type="hidden" name="name'.$counter.
2209: '" value="'.$env{'form.fullname'}.'" />'."\n";
2210: if ($env{'form.handgrade'} eq 'no') {
2211: $result.='<p class="LC_info">'
2212: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2213: ."</p>\n";
2214: }
2215:
2216: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2217: my $fullname;
2218: my $col_fullnames = [];
2219: if ($env{'form.handgrade'} eq 'yes') {
2220: (my $sub_result,$fullname,$col_fullnames)=
2221: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2222: $counter);
2223: $result.=$sub_result;
2224: }
2225: $request->print($result."\n");
2226:
2227: # print student answer/submission
2228: # Options are (1) Handgraded submission only
2229: # (2) Last submission, includes submission that is not handgraded
2230: # (for multi-response type part)
2231: # (3) Last submission plus the parts info
2232: # (4) The whole record for this student
2233:
2234: my ($string,$timestamp)= &get_last_submission(\%record);
2235:
2236: my $lastsubonly;
2237:
2238: if ($$timestamp eq '') {
2239: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2240: } else {
2241: $lastsubonly =
2242: '<div class="LC_grade_submissions_body">'
2243: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2244:
2245: my %seenparts;
2246: my @part_response_id = &flatten_responseType($responseType);
2247: foreach my $part (@part_response_id) {
2248: next if ($env{'form.lastSub'} eq 'hdgrade'
2249: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2250:
2251: my ($partid,$respid) = @{ $part };
2252: my $display_part=&get_display_part($partid,$symb);
2253: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2254: if (exists($seenparts{$partid})) { next; }
2255: $seenparts{$partid}=1;
2256: $request->print(
2257: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2258: ' <b>'.&mt('Collaborative submission by: [_1]',
2259: '<a href="javascript:viewSubmitter(\''.
2260: $env{"form.$uname:$udom:$partid:submitted_by"}.
2261: '\');" target="_self">'.
2262: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2263: '<br />');
2264: next;
2265: }
2266: my $responsetype = $responseType->{$partid}->{$respid};
2267: if (!exists($record{"resource.$partid.$respid.submission"})) {
2268: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2269: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2270: ' <span class="LC_internal_info">'.
2271: '('.&mt('Response ID: [_1]',$respid).')'.
2272: '</span> '.
2273: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2274: next;
2275: }
2276: foreach my $submission (@$string) {
2277: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2278: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2279: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2280: # Similarity check
2281: my $similar='';
2282: my ($type,$trial,$rndseed);
2283: if ($hide eq 'rand') {
2284: $type = 'randomizetry';
2285: $trial = $record{"resource.$partid.tries"};
2286: $rndseed = $record{"resource.$partid.rndseed"};
2287: }
2288: if ($env{'form.checkPlag'}) {
2289: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2290: &most_similar($uname,$udom,$symb,$subval);
2291: if ($osim) {
2292: $osim=int($osim*100.0);
2293: my %old_course_desc =
2294: &Apache::lonnet::coursedescription($ocrsid,
2295: {'one_time' => 1});
2296:
2297: if ($hide eq 'anon') {
2298: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2299: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2300: } else {
2301: $similar="<hr /><h3><span class=\"LC_warning\">".
2302: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2303: $osim,
2304: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2305: $old_course_desc{'description'},
2306: $old_course_desc{'num'},
2307: $old_course_desc{'domain'}).
2308: '</span></h3><blockquote><i>'.
2309: &keywords_highlight($oessay).
2310: '</i></blockquote><hr />';
2311: }
2312: }
2313: }
2314: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2315: undef,$type,$trial,$rndseed);
2316: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2317: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2318: my $display_part=&get_display_part($partid,$symb);
2319: $lastsubonly.='<div class="LC_grade_submission_part">'.
2320: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2321: ' <span class="LC_internal_info">'.
2322: '('.&mt('Response ID: [_1]',$respid).')'.
2323: '</span> ';
2324: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2325: if (@$files) {
2326: if ($hide eq 'anon') {
2327: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2328: } else {
2329: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2330: .'<br /><span class="LC_warning">';
2331: if(@$files == 1) {
2332: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2333: } else {
2334: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2335: }
2336: $lastsubonly .= '</span>';
2337:
2338: foreach my $file (@$files) {
2339: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2340: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2341: }
2342: }
2343: $lastsubonly.='<br />';
2344: }
2345: if ($hide eq 'anon') {
2346: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2347: } else {
2348: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
2349: &cleanRecord($subval,$responsetype,$symb,$partid,
2350: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2351: }
2352: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2353: $lastsubonly.='</div>';
2354: }
2355: }
2356: }
2357: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2358: }
2359: $request->print($lastsubonly);
2360: if ($env{'form.lastSub'} eq 'datesub') {
2361: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2362: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2363: }
2364: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2365: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2366: $env{'request.course.id'},
2367: $last,'.submission',
2368: 'Apache::grades::keywords_highlight'));
2369: }
2370:
2371: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2372: .$udom.'" />'."\n");
2373: # return if view submission with no grading option
2374: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2375: my $toGrade.='<input type="button" value="Grade Student" '.
2376: 'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
2377: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2378: $toGrade.='</div>'."\n";
2379: if (($env{'form.command'} eq 'submission') ||
2380: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2381: $toGrade.='</form>'.&show_grading_menu_form($symb);
2382: }
2383: $request->print($toGrade);
2384: return;
2385: } else {
2386: $request->print('</div>'."\n");
2387: }
2388:
2389: # essay grading message center
2390: if ($env{'form.handgrade'} eq 'yes') {
2391: my $result='<div class="LC_grade_message_center">';
2392:
2393: $result.='<div class="LC_grade_message_center_header">'.
2394: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2395: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2396: my $msgfor = $givenn.' '.$lastname;
2397: if (scalar(@$col_fullnames) > 0) {
2398: my $lastone = pop(@$col_fullnames);
2399: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2400: }
2401: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2402: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2403: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2404: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2405: ',\''.$msgfor.'\');" target="_self">'.
2406: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2407: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2408: ' <img src="'.$request->dir_config('lonIconsURL').
2409: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2410: '<br /> ('.
2411: &mt('Message will be sent when you click on Save & Next below.').")\n";
2412: $result.='</div></div>';
2413: $request->print($result);
2414: }
2415:
2416: my %seen = ();
2417: my @partlist;
2418: my @gradePartRespid;
2419: my @part_response_id = &flatten_responseType($responseType);
2420: $request->print(
2421: '<div class="LC_Box">'
2422: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2423: );
2424: $request->print(&gradeBox_start());
2425: foreach my $part_response_id (@part_response_id) {
2426: my ($partid,$respid) = @{ $part_response_id };
2427: my $part_resp = join('_',@{ $part_response_id });
2428: next if ($seen{$partid} > 0);
2429: $seen{$partid}++;
2430: next if ($$handgrade{$part_resp} ne 'yes'
2431: && $env{'form.lastSub'} eq 'hdgrade');
2432: push(@partlist,$partid);
2433: push(@gradePartRespid,$partid.'.'.$respid);
2434: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2435: }
2436: $request->print(&gradeBox_end()); # </div>
2437: $request->print('</div>');
2438:
2439: $request->print('<div class="LC_grade_info_links">');
2440: $request->print('</div>');
2441:
2442: $result='<input type="hidden" name="partlist'.$counter.
2443: '" value="'.(join ":",@partlist).'" />'."\n";
2444: $result.='<input type="hidden" name="gradePartRespid'.
2445: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2446: my $ctr = 0;
2447: while ($ctr < scalar(@partlist)) {
2448: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2449: $partlist[$ctr].'" />'."\n";
2450: $ctr++;
2451: }
2452: $request->print($result.''."\n");
2453:
2454: # Done with printing info for one student
2455:
2456: $request->print('</div>');#LC_grade_show_user
2457:
2458:
2459: # print end of form
2460: if ($counter == $total) {
2461: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2462: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2463: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2464: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2465: my $ntstu ='<select name="NTSTU">'.
2466: '<option>1</option><option>2</option>'.
2467: '<option>3</option><option>5</option>'.
2468: '<option>7</option><option>10</option></select>'."\n";
2469: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2470: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2471: $endform.=&mt('[_1]student(s)',$ntstu);
2472: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2473: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2474: '<input type="button" value="'.&mt('Next').'" '.
2475: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2476: $endform.='<span class="LC_warning">'.
2477: &mt('(Next and Previous (student) do not save the scores.)').
2478: '</span>'."\n" ;
2479: $endform.="<input type='hidden' value='".&get_increment().
2480: "' name='increment' />";
2481: $endform.='</td></tr></table></form>';
2482: $endform.=&show_grading_menu_form($symb);
2483: $request->print($endform);
2484: }
2485: return '';
2486: }
2487:
2488: sub check_collaborators {
2489: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2490: my ($result,@col_fullnames);
2491: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2492: foreach my $part (keys(%$handgrade)) {
2493: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2494: '.maxcollaborators',
2495: $symb,$udom,$uname);
2496: next if ($ncol <= 0);
2497: $part =~ s/\_/\./g;
2498: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2499: my (@good_collaborators, @bad_collaborators);
2500: foreach my $possible_collaborator
2501: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2502: $possible_collaborator =~ s/[\$\^\(\)]//g;
2503: next if ($possible_collaborator eq '');
2504: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2505: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2506: next if ($co_name eq $uname && $co_dom eq $udom);
2507: # Doing this grep allows 'fuzzy' specification
2508: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2509: keys(%$classlist));
2510: if (! scalar(@matches)) {
2511: push(@bad_collaborators, $possible_collaborator);
2512: } else {
2513: push(@good_collaborators, @matches);
2514: }
2515: }
2516: if (scalar(@good_collaborators) != 0) {
2517: $result.='<br />'.&mt('Collaborators:').'<ol>';
2518: foreach my $name (@good_collaborators) {
2519: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2520: push(@col_fullnames, $givenn.' '.$lastname);
2521: $result.='<li>'.$fullname->{$name}.'</li>';
2522: }
2523: $result.='</ol><br />'."\n";
2524: my ($part)=split(/\./,$part);
2525: $result.='<input type="hidden" name="collaborator'.$counter.
2526: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2527: "\n";
2528: }
2529: if (scalar(@bad_collaborators) > 0) {
2530: $result.='<div class="LC_warning">';
2531: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2532: $result .= '</div>';
2533: }
2534: if (scalar(@bad_collaborators > $ncol)) {
2535: $result .= '<div class="LC_warning">';
2536: $result .= &mt('This student has submitted too many '.
2537: 'collaborators. Maximum is [_1].',$ncol);
2538: $result .= '</div>';
2539: }
2540: }
2541: return ($result,$fullname,\@col_fullnames);
2542: }
2543:
2544: #--- Retrieve the last submission for all the parts
2545: sub get_last_submission {
2546: my ($returnhash)=@_;
2547: my (@string,$timestamp,%lasthidden);
2548: if ($$returnhash{'version'}) {
2549: my %lasthash=();
2550: my ($version);
2551: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2552: foreach my $key (sort(split(/\:/,
2553: $$returnhash{$version.':keys'}))) {
2554: $lasthash{$key}=$$returnhash{$version.':'.$key};
2555: $timestamp =
2556: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2557: }
2558: }
2559: my (%typeparts,%randombytry);
2560: my $showsurv =
2561: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2562: foreach my $key (sort(keys(%lasthash))) {
2563: if ($key =~ /\.type$/) {
2564: if (($lasthash{$key} eq 'anonsurvey') ||
2565: ($lasthash{$key} eq 'anonsurveycred') ||
2566: ($lasthash{$key} eq 'randomizetry')) {
2567: my ($ign,@parts) = split(/\./,$key);
2568: pop(@parts);
2569: my $id = join('.',@parts);
2570: if ($lasthash{$key} eq 'randomizetry') {
2571: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2572: } else {
2573: unless ($showsurv) {
2574: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2575: }
2576: }
2577: delete($lasthash{$key});
2578: }
2579: }
2580: }
2581: my @hidden = keys(%typeparts);
2582: my @randomize = keys(%randombytry);
2583: foreach my $key (keys(%lasthash)) {
2584: next if ($key !~ /\.submission$/);
2585: my $hide;
2586: if (@hidden) {
2587: foreach my $id (@hidden) {
2588: if ($key =~ /^\Q$id\E/) {
2589: $hide = 'anon';
2590: last;
2591: }
2592: }
2593: }
2594: unless ($hide) {
2595: if (@randomize) {
2596: foreach my $id (@hidden) {
2597: if ($key =~ /^\Q$id\E/) {
2598: $hide = 'rand';
2599: last;
2600: }
2601: }
2602: }
2603: }
2604: my ($partid,$foo) = split(/submission$/,$key);
2605: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2606: '<span class="LC_warning">Draft Copy</span> ' : '';
2607: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2608: }
2609: }
2610: if (!@string) {
2611: $string[0] =
2612: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2613: }
2614: return (\@string,\$timestamp);
2615: }
2616:
2617: #--- High light keywords, with style choosen by user.
2618: sub keywords_highlight {
2619: my $string = shift;
2620: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2621: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2622: (my $styleoff = $styleon) =~ s/\</\<\//;
2623: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2624: foreach my $keyword (@keylist) {
2625: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2626: }
2627: return $string;
2628: }
2629:
2630: # For Tasks provide a mechanism to display previous version for one specific student
2631:
2632: sub show_previous_task_version {
2633: my ($request,$symb) = @_;
2634: if ($symb eq '') {
2635: $request->print("Unable to handle ambiguous references.");
2636:
2637: return '';
2638: }
2639: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2640: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2641: if (!&canview($usec)) {
2642: $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
2643: $uname.':'.$udom.' in section '.$usec.' in course id '.
2644: $env{'request.course.id'}.')</span>');
2645: return;
2646: }
2647: my $mode = 'both';
2648: my $isTask = ($symb =~/\.task$/);
2649: if ($isTask) {
2650: if ($env{'form.previousversion'} =~ /^\d+$/) {
2651: if ($env{'form.fullname'} eq '') {
2652: $env{'form.fullname'} =
2653: &Apache::loncommon::plainname($uname,$udom,'lastname');
2654: }
2655: my $probtitle=&Apache::lonnet::gettitle($symb);
2656: $request->print("\n\n".
2657: '<div class="LC_grade_show_user">'.
2658: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2659: '</h2>'."\n");
2660: &Apache::lonxml::clear_problem_counter();
2661: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2662: {'previousversion' => $env{'form.previousversion'} }));
2663: $request->print("\n</div>");
2664: }
2665: }
2666: return;
2667: }
2668:
2669: sub choose_task_version_form {
2670: my ($symb,$uname,$udom,$nomenu) = @_;
2671: my $isTask = ($symb =~/\.task$/);
2672: my ($current,$version,$result,$js,$displayed,$rowtitle);
2673: if ($isTask) {
2674: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2675: $udom,$uname);
2676: if (($record{'resource.0.version'} eq '') ||
2677: ($record{'resource.0.version'} < 2)) {
2678: return ($record{'resource.0.version'},
2679: $record{'resource.0.version'},$result,$js);
2680: } else {
2681: $current = $record{'resource.0.version'};
2682: }
2683: if ($env{'form.previousversion'}) {
2684: $displayed = $env{'form.previousversion'};
2685: $rowtitle = &mt('Choose another version:')
2686: } else {
2687: $displayed = $current;
2688: $rowtitle = &mt('Show earlier version:');
2689: }
2690: $result = '<div class="LC_left_float">';
2691: my $list;
2692: my $numversions = 0;
2693: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2694: if ($i == $current) {
2695: if (!$env{'form.previousversion'} || $nomenu) {
2696: next;
2697: } else {
2698: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2699: $numversions ++;
2700: }
2701: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2702: unless ($i == $env{'form.previousversion'}) {
2703: $numversions ++;
2704: }
2705: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2706: }
2707: }
2708: if ($numversions) {
2709: $symb = &HTML::Entities::encode($symb,'<>"&');
2710: $result .=
2711: '<form name="getprev" method="post" action=""'.
2712: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2713: &Apache::loncommon::start_data_table().
2714: &Apache::loncommon::start_data_table_row().
2715: '<th align="left">'.$rowtitle.'</th>'.
2716: '<td><select name="version">'.
2717: '<option>'.&mt('Select').'</option>'.
2718: $list.
2719: '</select></td>'.
2720: &Apache::loncommon::end_data_table_row();
2721: unless ($nomenu) {
2722: $result .= &Apache::loncommon::start_data_table_row().
2723: '<th align="left">'.&mt('Open in new window').'</th>'.
2724: '<td><span class="LC_nobreak">'.
2725: '<label><input type="radio" name="prevwin" value="1" />'.
2726: &mt('Yes').'</label>'.
2727: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2728: '</span></td>'.
2729: &Apache::loncommon::end_data_table_row();
2730: }
2731: $result .=
2732: &Apache::loncommon::start_data_table_row().
2733: '<th align="left"> </th>'.
2734: '<td>'.
2735: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2736: '</td>'.
2737: &Apache::loncommon::end_data_table_row().
2738: &Apache::loncommon::end_data_table().
2739: '</form>';
2740: $js = &previous_display_javascript($nomenu,$current);
2741: } elsif ($displayed && $nomenu) {
2742: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2743: } else {
2744: $result .= &mt('No previous versions to show for this student');
2745: }
2746: $result .= '</div>';
2747: }
2748: return ($current,$displayed,$result,$js);
2749: }
2750:
2751: sub previous_display_javascript {
2752: my ($nomenu,$current) = @_;
2753: my $js = <<"JSONE";
2754: <script type="text/javascript">
2755: // <![CDATA[
2756: function previousVersion(uname,udom,symb) {
2757: var current = '$current';
2758: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2759: var prevstr = new RegExp("^\\\\d+\$");
2760: if (!prevstr.test(version)) {
2761: return false;
2762: }
2763: var url = '';
2764: if (version == current) {
2765: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2766: } else {
2767: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2768: }
2769: JSONE
2770: if ($nomenu) {
2771: $js .= <<"JSTWO";
2772: document.location.href = url;
2773: JSTWO
2774: } else {
2775: $js .= <<"JSTHREE";
2776: var newwin = 0;
2777: for (var i=0; i<document.getprev.prevwin.length; i++) {
2778: if (document.getprev.prevwin[i].checked == true) {
2779: newwin = document.getprev.prevwin[i].value;
2780: }
2781: }
2782: if (newwin == 1) {
2783: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2784: url = url+'&inhibitmenu=yes';
2785: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2786: previousWin = window.open(url,'',options,1);
2787: } else {
2788: previousWin.location.href = url;
2789: }
2790: previousWin.focus();
2791: return false;
2792: } else {
2793: document.location.href = url;
2794: return false;
2795: }
2796: JSTHREE
2797: }
2798: $js .= <<"ENDJS";
2799: return false;
2800: }
2801: // ]]>
2802: </script>
2803: ENDJS
2804:
2805: }
2806:
2807: #--- Called from submission routine
2808: sub processHandGrade {
2809: my ($request) = shift;
2810: my ($symb) = &get_symb($request);
2811: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2812: my $button = $env{'form.gradeOpt'};
2813: my $ngrade = $env{'form.NCT'};
2814: my $ntstu = $env{'form.NTSTU'};
2815: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2816: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2817:
2818: if ($button eq 'Save & Next') {
2819: my $ctr = 0;
2820: while ($ctr < $ngrade) {
2821: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2822: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2823: if ($errorflag eq 'no_score') {
2824: $ctr++;
2825: next;
2826: }
2827: if ($errorflag eq 'not_allowed') {
2828: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2829: $ctr++;
2830: next;
2831: }
2832: my $includemsg = $env{'form.includemsg'.$ctr};
2833: my ($subject,$message,$msgstatus) = ('','','');
2834: my $restitle = &Apache::lonnet::gettitle($symb);
2835: my ($feedurl,$showsymb) =
2836: &get_feedurl_and_symb($symb,$uname,$udom);
2837: my $messagetail;
2838: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2839: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2840: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2841: $subject.=' ['.$restitle.']';
2842: my (@msgnum) = split(/,/,$includemsg);
2843: foreach (@msgnum) {
2844: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2845: }
2846: $message =&Apache::lonfeedback::clear_out_html($message);
2847: if ($env{'form.withgrades'.$ctr}) {
2848: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2849: $messagetail = " for <a href=\"".
2850: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2851: }
2852: $msgstatus =
2853: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2854: $message.$messagetail,
2855: undef,$feedurl,undef,
2856: undef,undef,$showsymb,
2857: $restitle);
2858: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2859: $msgstatus.'<br />');
2860: }
2861: if ($env{'form.collaborator'.$ctr}) {
2862: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2863: foreach my $collabstr (@collabstrs) {
2864: my ($part,@collaborators) = split(/:/,$collabstr);
2865: foreach my $collaborator (@collaborators) {
2866: my ($errorflag,$pts,$wgt) =
2867: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2868: $env{'form.unamedom'.$ctr},$part);
2869: if ($errorflag eq 'not_allowed') {
2870: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2871: next;
2872: } elsif ($message ne '') {
2873: my ($baseurl,$showsymb) =
2874: &get_feedurl_and_symb($symb,$collaborator,
2875: $udom);
2876: if ($env{'form.withgrades'.$ctr}) {
2877: $messagetail = " for <a href=\"".
2878: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2879: }
2880: $msgstatus =
2881: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2882: }
2883: }
2884: }
2885: }
2886: $ctr++;
2887: }
2888: }
2889:
2890: if ($env{'form.handgrade'} eq 'yes') {
2891: # Keywords sorted in alphabatical order
2892: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2893: my %keyhash = ();
2894: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2895: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2896: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2897: $env{'form.keywords'} = join(' ',@keywords);
2898: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2899: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2900: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2901: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2902: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2903:
2904: # message center - Order of message gets changed. Blank line is eliminated.
2905: # New messages are saved in env for the next student.
2906: # All messages are saved in nohist_handgrade.db
2907: my ($ctr,$idx) = (1,1);
2908: while ($ctr <= $env{'form.savemsgN'}) {
2909: if ($env{'form.savemsg'.$ctr} ne '') {
2910: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2911: $idx++;
2912: }
2913: $ctr++;
2914: }
2915: $ctr = 0;
2916: while ($ctr < $ngrade) {
2917: if ($env{'form.newmsg'.$ctr} ne '') {
2918: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2919: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2920: $idx++;
2921: }
2922: $ctr++;
2923: }
2924: $env{'form.savemsgN'} = --$idx;
2925: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2926: my $putresult = &Apache::lonnet::put
2927: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2928: }
2929: # Called by Save & Refresh from Highlight Attribute Window
2930: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2931: if ($env{'form.refresh'} eq 'on') {
2932: my ($ctr,$total) = (0,0);
2933: while ($ctr < $ngrade) {
2934: $total++ if $env{'form.unamedom'.$ctr} ne '';
2935: $ctr++;
2936: }
2937: $env{'form.NTSTU'}=$ngrade;
2938: $ctr = 0;
2939: while ($ctr < $total) {
2940: my $processUser = $env{'form.unamedom'.$ctr};
2941: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2942: $env{'form.fullname'} = $$fullname{$processUser};
2943: &submission($request,$ctr,$total-1);
2944: $ctr++;
2945: }
2946: return '';
2947: }
2948:
2949: # Go directly to grade student - from submission or link from chart page
2950: if ($button eq 'Grade Student') {
2951: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2952: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2953: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2954: $env{'form.fullname'} = $$fullname{$processUser};
2955: &submission($request,0,0);
2956: return '';
2957: }
2958:
2959: # Get the next/previous one or group of students
2960: my $firststu = $env{'form.unamedom0'};
2961: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2962: my $ctr = 2;
2963: while ($laststu eq '') {
2964: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2965: $ctr++;
2966: $laststu = $firststu if ($ctr > $ngrade);
2967: }
2968:
2969: my (@parsedlist,@nextlist);
2970: my ($nextflg) = 0;
2971: foreach my $item (sort
2972: {
2973: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2974: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2975: }
2976: return $a cmp $b;
2977: } (keys(%$fullname))) {
2978: if ($nextflg == 1 && $button =~ /Next$/) {
2979: push(@parsedlist,$item);
2980: }
2981: $nextflg = 1 if ($item eq $laststu);
2982: if ($button eq 'Previous') {
2983: last if ($item eq $firststu);
2984: push(@parsedlist,$item);
2985: }
2986: }
2987: $ctr = 0;
2988: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2989: my $res_error;
2990: my ($partlist) = &response_type($symb,\$res_error);
2991: if ($res_error) {
2992: $request->print(&navmap_errormsg());
2993: return;
2994: }
2995: foreach my $student (@parsedlist) {
2996: my $submitonly=$env{'form.submitonly'};
2997: my ($uname,$udom) = split(/:/,$student);
2998:
2999: if ($submitonly eq 'queued') {
3000: my %queue_status =
3001: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
3002: $udom,$uname);
3003: next if (!defined($queue_status{'gradingqueue'}));
3004: }
3005:
3006: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
3007: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
3008: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
3009: my $submitted = 0;
3010: my $ungraded = 0;
3011: my $incorrect = 0;
3012: foreach my $item (keys(%status)) {
3013: $submitted = 1 if ($status{$item} ne 'nothing');
3014: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
3015: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
3016: my ($foo,$partid,$foo1) = split(/\./,$item);
3017: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
3018: $submitted = 0;
3019: }
3020: }
3021: next if (!$submitted && ($submitonly eq 'yes' ||
3022: $submitonly eq 'incorrect' ||
3023: $submitonly eq 'graded'));
3024: next if (!$ungraded && ($submitonly eq 'graded'));
3025: next if (!$incorrect && $submitonly eq 'incorrect');
3026: }
3027: push(@nextlist,$student) if ($ctr < $ntstu);
3028: last if ($ctr == $ntstu);
3029: $ctr++;
3030: }
3031:
3032: $ctr = 0;
3033: my $total = scalar(@nextlist)-1;
3034:
3035: foreach (sort(@nextlist)) {
3036: my ($uname,$udom,$submitter) = split(/:/);
3037: $env{'form.student'} = $uname;
3038: $env{'form.userdom'} = $udom;
3039: $env{'form.fullname'} = $$fullname{$_};
3040: &submission($request,$ctr,$total);
3041: $ctr++;
3042: }
3043: if ($total < 0) {
3044: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
3045: $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
3046: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
3047: $the_end.=&show_grading_menu_form($symb);
3048: $request->print($the_end);
3049: }
3050: return '';
3051: }
3052:
3053: #---- Save the score and award for each student, if changed
3054: sub saveHandGrade {
3055: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3056: my @version_parts;
3057: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3058: $env{'request.course.id'});
3059: if (!&canmodify($usec)) { return('not_allowed'); }
3060: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3061: my @parts_graded;
3062: my %newrecord = ();
3063: my ($pts,$wgt) = ('','');
3064: my %aggregate = ();
3065: my $aggregateflag = 0;
3066: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3067: foreach my $new_part (@parts) {
3068: #collaborator ($submi may vary for different parts
3069: if ($submitter && $new_part ne $part) { next; }
3070: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3071: if ($dropMenu eq 'excused') {
3072: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3073: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3074: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3075: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3076: }
3077: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3078: }
3079: } elsif ($dropMenu eq 'reset status'
3080: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3081: foreach my $key (keys(%record)) {
3082: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3083: }
3084: $newrecord{'resource.'.$new_part.'.regrader'}=
3085: "$env{'user.name'}:$env{'user.domain'}";
3086: my $totaltries = $record{'resource.'.$part.'.tries'};
3087:
3088: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3089: [$new_part]);
3090: my $aggtries =$totaltries;
3091: if ($last_resets{$new_part}) {
3092: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3093: $new_part);
3094: }
3095:
3096: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3097: if ($aggtries > 0) {
3098: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3099: $aggregateflag = 1;
3100: }
3101: } elsif ($dropMenu eq '') {
3102: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3103: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3104: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3105: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3106: next;
3107: }
3108: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3109: $env{'form.WGT'.$newflg.'_'.$new_part};
3110: my $partial= $pts/$wgt;
3111: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3112: #do not update score for part if not changed.
3113: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3114: next;
3115: } else {
3116: push(@parts_graded,$new_part);
3117: }
3118: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3119: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3120: }
3121: my $reckey = 'resource.'.$new_part.'.solved';
3122: if ($partial == 0) {
3123: if ($record{$reckey} ne 'incorrect_by_override') {
3124: $newrecord{$reckey} = 'incorrect_by_override';
3125: }
3126: } else {
3127: if ($record{$reckey} ne 'correct_by_override') {
3128: $newrecord{$reckey} = 'correct_by_override';
3129: }
3130: }
3131: if ($submitter &&
3132: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3133: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3134: }
3135: $newrecord{'resource.'.$new_part.'.regrader'}=
3136: "$env{'user.name'}:$env{'user.domain'}";
3137: }
3138: # unless problem has been graded, set flag to version the submitted files
3139: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3140: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3141: $dropMenu eq 'reset status')
3142: {
3143: push(@version_parts,$new_part);
3144: }
3145: }
3146: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3147: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3148:
3149: if (%newrecord) {
3150: if (@version_parts) {
3151: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3152: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3153: @newrecord{@changed_keys} = @record{@changed_keys};
3154: foreach my $new_part (@version_parts) {
3155: &handback_files($request,$symb,$stuname,$domain,$newflg,
3156: $new_part,\%newrecord);
3157: }
3158: }
3159: &Apache::lonnet::cstore(\%newrecord,$symb,
3160: $env{'request.course.id'},$domain,$stuname);
3161: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3162: $cdom,$cnum,$domain,$stuname);
3163: }
3164: if ($aggregateflag) {
3165: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3166: $cdom,$cnum);
3167: }
3168: return ('',$pts,$wgt);
3169: }
3170:
3171: sub check_and_remove_from_queue {
3172: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3173: my @ungraded_parts;
3174: foreach my $part (@{$parts}) {
3175: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3176: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3177: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3178: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3179: ) {
3180: push(@ungraded_parts, $part);
3181: }
3182: }
3183: if ( !@ungraded_parts ) {
3184: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3185: $cnum,$domain,$stuname);
3186: }
3187: }
3188:
3189: sub handback_files {
3190: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3191: my $portfolio_root = '/userfiles/portfolio';
3192: my $res_error;
3193: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3194: if ($res_error) {
3195: $request->print('<br />'.&navmap_errormsg().'<br />');
3196: return;
3197: }
3198: my @handedback;
3199: my $file_msg;
3200: my @part_response_id = &flatten_responseType($responseType);
3201: foreach my $part_response_id (@part_response_id) {
3202: my ($part_id,$resp_id) = @{ $part_response_id };
3203: my $part_resp = join('_',@{ $part_response_id });
3204: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3205: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3206: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3207: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3208: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3209: my ($directory,$answer_file) =
3210: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3211: my ($answer_name,$answer_ver,$answer_ext) =
3212: &file_name_version_ext($answer_file);
3213: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3214: my $getpropath = 1;
3215: my ($dir_list,$listerror) =
3216: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3217: $domain,$stuname,$getpropath);
3218: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3219: # fix filename
3220: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3221: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3222: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3223: $save_file_name);
3224: if ($result !~ m|^/uploaded/|) {
3225: $request->print('<br /><span class="LC_error">'.
3226: &mt('An error occurred ([_1]) while trying to upload [_2].',
3227: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3228: '</span>');
3229: } else {
3230: # mark the file as read only
3231: push(@handedback,$save_file_name);
3232: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3233: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3234: }
3235: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3236: $file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3237:
3238: }
3239: $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>'));
3240: }
3241: }
3242: }
3243: }
3244: if (@handedback > 0) {
3245: $request->print('<br />');
3246: my @what = ($symb,$env{'request.course.id'},'handback');
3247: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3248: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3249: my ($subject,$message);
3250: if (scalar(@handedback) == 1) {
3251: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3252: } else {
3253: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3254: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3255: }
3256: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3257: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3258: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3259: my ($feedurl,$showsymb) =
3260: &get_feedurl_and_symb($symb,$domain,$stuname);
3261: my $restitle = &Apache::lonnet::gettitle($symb);
3262: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3263: my $msgstatus =
3264: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3265: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3266: $restitle);
3267: if ($msgstatus) {
3268: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3269: }
3270: }
3271: return;
3272: }
3273:
3274: sub get_feedurl_and_symb {
3275: my ($symb,$uname,$udom) = @_;
3276: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3277: $url = &Apache::lonnet::clutter($url);
3278: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3279: $symb,$udom,$uname);
3280: if ($encrypturl =~ /^yes$/i) {
3281: &Apache::lonenc::encrypted(\$url,1);
3282: &Apache::lonenc::encrypted(\$symb,1);
3283: }
3284: return ($url,$symb);
3285: }
3286:
3287: sub get_submitted_files {
3288: my ($udom,$uname,$partid,$respid,$record) = @_;
3289: my @files;
3290: if ($$record{"resource.$partid.$respid.portfiles"}) {
3291: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3292: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3293: push(@files,$file_url.$file);
3294: }
3295: }
3296: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3297: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3298: }
3299: return (\@files);
3300: }
3301:
3302: # ----------- Provides number of tries since last reset.
3303: sub get_num_tries {
3304: my ($record,$last_reset,$part) = @_;
3305: my $timestamp = '';
3306: my $num_tries = 0;
3307: if ($$record{'version'}) {
3308: for (my $version=$$record{'version'};$version>=1;$version--) {
3309: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3310: $timestamp = $$record{$version.':timestamp'};
3311: if ($timestamp > $last_reset) {
3312: $num_tries ++;
3313: } else {
3314: last;
3315: }
3316: }
3317: }
3318: }
3319: return $num_tries;
3320: }
3321:
3322: # ----------- Determine decrements required in aggregate totals
3323: sub decrement_aggs {
3324: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3325: my %decrement = (
3326: attempts => 0,
3327: users => 0,
3328: correct => 0
3329: );
3330: $decrement{'attempts'} = $aggtries;
3331: if ($solvedstatus =~ /^correct/) {
3332: $decrement{'correct'} = 1;
3333: }
3334: if ($aggtries == $totaltries) {
3335: $decrement{'users'} = 1;
3336: }
3337: foreach my $type (keys(%decrement)) {
3338: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3339: }
3340: return;
3341: }
3342:
3343: # ----------- Determine timestamps for last reset of aggregate totals for parts
3344: sub get_last_resets {
3345: my ($symb,$courseid,$partids) =@_;
3346: my %last_resets;
3347: my $cdom = $env{'course.'.$courseid.'.domain'};
3348: my $cname = $env{'course.'.$courseid.'.num'};
3349: my @keys;
3350: foreach my $part (@{$partids}) {
3351: push(@keys,"$symb\0$part\0resettime");
3352: }
3353: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3354: $cdom,$cname);
3355: foreach my $part (@{$partids}) {
3356: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3357: }
3358: return %last_resets;
3359: }
3360:
3361: # ----------- Handles creating versions for portfolio files as answers
3362: sub version_portfiles {
3363: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3364: my $version_parts = join('|',@$v_flag);
3365: my @returned_keys;
3366: my $parts = join('|', @$parts_graded);
3367: my $portfolio_root = '/userfiles/portfolio';
3368: foreach my $key (keys(%$record)) {
3369: my $new_portfiles;
3370: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3371: my @versioned_portfiles;
3372: my @portfiles = split(/\s*,\s*/,$$record{$key});
3373: foreach my $file (@portfiles) {
3374: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3375: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3376: my ($answer_name,$answer_ver,$answer_ext) =
3377: &file_name_version_ext($answer_file);
3378: my $getpropath = 1;
3379: my ($dir_list,$listerror) =
3380: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3381: $stu_name,$getpropath);
3382: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3383: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3384: if ($new_answer ne 'problem getting file') {
3385: push(@versioned_portfiles, $directory.$new_answer);
3386: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3387: [$directory.$new_answer],
3388: [$symb,$env{'request.course.id'},'graded']);
3389: }
3390: }
3391: $$record{$key} = join(',',@versioned_portfiles);
3392: push(@returned_keys,$key);
3393: }
3394: }
3395: return (@returned_keys);
3396: }
3397:
3398: sub get_next_version {
3399: my ($answer_name, $answer_ext, $dir_list) = @_;
3400: my $version;
3401: if (ref($dir_list) eq 'ARRAY') {
3402: foreach my $row (@{$dir_list}) {
3403: my ($file) = split(/\&/,$row,2);
3404: my ($file_name,$file_version,$file_ext) =
3405: &file_name_version_ext($file);
3406: if (($file_name eq $answer_name) &&
3407: ($file_ext eq $answer_ext)) {
3408: # gets here if filename and extension match,
3409: # regardless of version
3410: if ($file_version ne '') {
3411: # a versioned file is found so save it for later
3412: if ($file_version > $version) {
3413: $version = $file_version;
3414: }
3415: }
3416: }
3417: }
3418: }
3419: $version ++;
3420: return($version);
3421: }
3422:
3423: sub version_selected_portfile {
3424: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3425: my ($answer_name,$answer_ver,$answer_ext) =
3426: &file_name_version_ext($file_name);
3427: my $new_answer;
3428: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3429: if($env{'form.copy'} eq '-1') {
3430: $new_answer = 'problem getting file';
3431: } else {
3432: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3433: my $copy_result = &Apache::lonnet::finishuserfileupload(
3434: $stu_name,$domain,'copy',
3435: '/portfolio'.$directory.$new_answer);
3436: }
3437: return ($new_answer);
3438: }
3439:
3440: sub file_name_version_ext {
3441: my ($file)=@_;
3442: my @file_parts = split(/\./, $file);
3443: my ($name,$version,$ext);
3444: if (@file_parts > 1) {
3445: $ext=pop(@file_parts);
3446: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3447: $version=pop(@file_parts);
3448: }
3449: $name=join('.',@file_parts);
3450: } else {
3451: $name=join('.',@file_parts);
3452: }
3453: return($name,$version,$ext);
3454: }
3455:
3456: #--------------------------------------------------------------------------------------
3457: #
3458: #-------------------------- Next few routines handles grading by section or whole class
3459: #
3460: #--- Javascript to handle grading by section or whole class
3461: sub viewgrades_js {
3462: my ($request) = shift;
3463:
3464: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3465: $request->print(<<VIEWJAVASCRIPT);
3466: <script type="text/javascript" language="javascript">
3467: function writePoint(partid,weight,point) {
3468: var radioButton = document.classgrade["RADVAL_"+partid];
3469: var textbox = document.classgrade["TEXTVAL_"+partid];
3470: if (point == "textval") {
3471: point = document.classgrade["TEXTVAL_"+partid].value;
3472: if (isNaN(point) || parseFloat(point) < 0) {
3473: alert("$alertmsg"+parseFloat(point));
3474: var resetbox = false;
3475: for (var i=0; i<radioButton.length; i++) {
3476: if (radioButton[i].checked) {
3477: textbox.value = i;
3478: resetbox = true;
3479: }
3480: }
3481: if (!resetbox) {
3482: textbox.value = "";
3483: }
3484: return;
3485: }
3486: if (parseFloat(point) > parseFloat(weight)) {
3487: var resp = confirm("You entered a value ("+parseFloat(point)+
3488: ") greater than the weight for the part. Accept?");
3489: if (resp == false) {
3490: textbox.value = "";
3491: return;
3492: }
3493: }
3494: for (var i=0; i<radioButton.length; i++) {
3495: radioButton[i].checked=false;
3496: if (parseFloat(point) == i) {
3497: radioButton[i].checked=true;
3498: }
3499: }
3500:
3501: } else {
3502: textbox.value = parseFloat(point);
3503: }
3504: for (i=0;i<document.classgrade.total.value;i++) {
3505: var user = document.classgrade["ctr"+i].value;
3506: user = user.replace(new RegExp(':', 'g'),"_");
3507: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3508: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3509: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3510: if (saveval != "correct") {
3511: scorename.value = point;
3512: if (selname[0].selected != true) {
3513: selname[0].selected = true;
3514: }
3515: }
3516: }
3517: document.classgrade["SELVAL_"+partid][0].selected = true;
3518: }
3519:
3520: function writeRadText(partid,weight) {
3521: var selval = document.classgrade["SELVAL_"+partid];
3522: var radioButton = document.classgrade["RADVAL_"+partid];
3523: var override = document.classgrade["FORCE_"+partid].checked;
3524: var textbox = document.classgrade["TEXTVAL_"+partid];
3525: if (selval[1].selected || selval[2].selected) {
3526: for (var i=0; i<radioButton.length; i++) {
3527: radioButton[i].checked=false;
3528:
3529: }
3530: textbox.value = "";
3531:
3532: for (i=0;i<document.classgrade.total.value;i++) {
3533: var user = document.classgrade["ctr"+i].value;
3534: user = user.replace(new RegExp(':', 'g'),"_");
3535: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3536: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3537: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3538: if ((saveval != "correct") || override) {
3539: scorename.value = "";
3540: if (selval[1].selected) {
3541: selname[1].selected = true;
3542: } else {
3543: selname[2].selected = true;
3544: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3545: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3546: }
3547: }
3548: }
3549: } else {
3550: for (i=0;i<document.classgrade.total.value;i++) {
3551: var user = document.classgrade["ctr"+i].value;
3552: user = user.replace(new RegExp(':', 'g'),"_");
3553: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3554: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3555: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3556: if ((saveval != "correct") || override) {
3557: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3558: selname[0].selected = true;
3559: }
3560: }
3561: }
3562: }
3563:
3564: function changeSelect(partid,user) {
3565: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3566: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3567: var point = textbox.value;
3568: var weight = document.classgrade["weight_"+partid].value;
3569:
3570: if (isNaN(point) || parseFloat(point) < 0) {
3571: alert("$alertmsg"+parseFloat(point));
3572: textbox.value = "";
3573: return;
3574: }
3575: if (parseFloat(point) > parseFloat(weight)) {
3576: var resp = confirm("You entered a value ("+parseFloat(point)+
3577: ") greater than the weight of the part. Accept?");
3578: if (resp == false) {
3579: textbox.value = "";
3580: return;
3581: }
3582: }
3583: selval[0].selected = true;
3584: }
3585:
3586: function changeOneScore(partid,user) {
3587: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3588: if (selval[1].selected || selval[2].selected) {
3589: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3590: if (selval[2].selected) {
3591: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3592: }
3593: }
3594: }
3595:
3596: function resetEntry(numpart) {
3597: for (ctpart=0;ctpart<numpart;ctpart++) {
3598: var partid = document.classgrade["partid_"+ctpart].value;
3599: var radioButton = document.classgrade["RADVAL_"+partid];
3600: var textbox = document.classgrade["TEXTVAL_"+partid];
3601: var selval = document.classgrade["SELVAL_"+partid];
3602: for (var i=0; i<radioButton.length; i++) {
3603: radioButton[i].checked=false;
3604:
3605: }
3606: textbox.value = "";
3607: selval[0].selected = true;
3608:
3609: for (i=0;i<document.classgrade.total.value;i++) {
3610: var user = document.classgrade["ctr"+i].value;
3611: user = user.replace(new RegExp(':', 'g'),"_");
3612: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3613: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3614: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3615: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3616: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3617: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3618: if (saveselval == "excused") {
3619: if (selname[1].selected == false) { selname[1].selected = true;}
3620: } else {
3621: if (selname[0].selected == false) {selname[0].selected = true};
3622: }
3623: }
3624: }
3625: }
3626:
3627: </script>
3628: VIEWJAVASCRIPT
3629: }
3630:
3631: #--- show scores for a section or whole class w/ option to change/update a score
3632: sub viewgrades {
3633: my ($request) = shift;
3634: &viewgrades_js($request);
3635:
3636: my ($symb) = &get_symb($request);
3637: #need to make sure we have the correct data for later EXT calls,
3638: #thus invalidate the cache
3639: &Apache::lonnet::devalidatecourseresdata(
3640: $env{'course.'.$env{'request.course.id'}.'.num'},
3641: $env{'course.'.$env{'request.course.id'}.'.domain'});
3642: &Apache::lonnet::clear_EXT_cache_status();
3643:
3644: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3645: $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
3646:
3647: #view individual student submission form - called using Javascript viewOneStudent
3648: $result.=&jscriptNform($symb);
3649:
3650: #beginning of class grading form
3651: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3652: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3653: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3654: '<input type="hidden" name="command" value="editgrades" />'."\n".
3655: &build_section_inputs().
3656: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3657: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3658: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3659:
3660: my ($common_header,$specific_header);
3661: if ($env{'form.section'} eq 'all') {
3662: $common_header = &mt('Assign Common Grade to Class');
3663: $specific_header = &mt('Assign Grade to Specific Students in Class');
3664: } elsif ($env{'form.section'} eq 'none') {
3665: $common_header = &mt('Assign Common Grade to Students in no Section');
3666: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3667: } else {
3668: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3669: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3670: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3671: }
3672: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3673: #radio buttons/text box for assigning points for a section or class.
3674: #handles different parts of a problem
3675: my $res_error;
3676: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3677: if ($res_error) {
3678: return &navmap_errormsg();
3679: }
3680: my %weight = ();
3681: my $ctsparts = 0;
3682: my %seen = ();
3683: my @part_response_id = &flatten_responseType($responseType);
3684: foreach my $part_response_id (@part_response_id) {
3685: my ($partid,$respid) = @{ $part_response_id };
3686: my $part_resp = join('_',@{ $part_response_id });
3687: next if $seen{$partid};
3688: $seen{$partid}++;
3689: my $handgrade=$$handgrade{$part_resp};
3690: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3691: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3692:
3693: my $display_part=&get_display_part($partid,$symb);
3694: my $radio.='<table border="0"><tr>';
3695: my $ctr = 0;
3696: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3697: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3698: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3699: ','.$ctr.')" />'.$ctr."</label></td>\n";
3700: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3701: $ctr++;
3702: }
3703: $radio.='</tr></table>';
3704: my $line = '<input type="text" name="TEXTVAL_'.
3705: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3706: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3707: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3708: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3709: '<select name="SELVAL_'.$partid.'" '.
3710: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3711: $weight{$partid}.')"> '.
3712: '<option selected="selected"> </option>'.
3713: '<option value="excused">'.&mt('excused').'</option>'.
3714: '<option value="reset status">'.&mt('reset status').'</option>'.
3715: '</select></td>'.
3716: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3717: $line.='<input type="hidden" name="partid_'.
3718: $ctsparts.'" value="'.$partid.'" />'."\n";
3719: $line.='<input type="hidden" name="weight_'.
3720: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3721:
3722: $result.=
3723: &Apache::loncommon::start_data_table_row()."\n".
3724: '<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>'.
3725: &Apache::loncommon::end_data_table_row()."\n";
3726: $ctsparts++;
3727: }
3728: $result.=&Apache::loncommon::end_data_table()."\n".
3729: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3730: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3731: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3732:
3733: #table listing all the students in a section/class
3734: #header of table
3735: $result.= '<h3>'.$specific_header.'</h3>'.
3736: &Apache::loncommon::start_data_table().
3737: &Apache::loncommon::start_data_table_header_row().
3738: '<th>'.&mt('No.').'</th>'.
3739: '<th>'.&nameUserString('header')."</th>\n";
3740: my $partserror;
3741: my (@parts) = sort(&getpartlist($symb,\$partserror));
3742: if ($partserror) {
3743: return &navmap_errormsg();
3744: }
3745: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3746: my @partids = ();
3747: foreach my $part (@parts) {
3748: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3749: my $narrowtext = &mt('Tries');
3750: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3751: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3752: my ($partid) = &split_part_type($part);
3753: push(@partids,$partid);
3754: my $display_part=&get_display_part($partid,$symb);
3755: if ($display =~ /^Partial Credit Factor/) {
3756: $result.='<th>'.
3757: &mt('Score Part: [_1][_2](weight = [_3])',
3758: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3759: next;
3760:
3761: } else {
3762: if ($display =~ /Problem Status/) {
3763: my $grade_status_mt = &mt('Grade Status');
3764: $display =~ s{Problem Status}{$grade_status_mt<br />};
3765: }
3766: my $part_mt = &mt('Part:');
3767: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3768: }
3769:
3770: $result.='<th>'.$display.'</th>'."\n";
3771: }
3772: $result.=&Apache::loncommon::end_data_table_header_row();
3773:
3774: my %last_resets =
3775: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3776:
3777: #get info for each student
3778: #list all the students - with points and grade status
3779: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3780: my $ctr = 0;
3781: foreach (sort
3782: {
3783: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3784: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3785: }
3786: return $a cmp $b;
3787: } (keys(%$fullname))) {
3788: $ctr++;
3789: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3790: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3791: }
3792: $result.=&Apache::loncommon::end_data_table();
3793: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3794: $result.='<input type="button" value="'.&mt('Save').'" '.
3795: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3796: if (scalar(%$fullname) eq 0) {
3797: my $colspan=3+scalar(@parts);
3798: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3799: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3800: $result='<span class="LC_warning">'.
3801: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3802: $section_display, $stu_status).
3803: '</span>';
3804: }
3805: $result.=&show_grading_menu_form($symb);
3806: return $result;
3807: }
3808:
3809: #--- call by previous routine to display each student
3810: sub viewstudentgrade {
3811: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3812: my ($uname,$udom) = split(/:/,$student);
3813: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3814: my %aggregates = ();
3815: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3816: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3817: "\n".$ctr.' </td><td> '.
3818: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3819: '\');" target="_self">'.$fullname.'</a> '.
3820: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3821: $student=~s/:/_/; # colon doen't work in javascript for names
3822: foreach my $apart (@$parts) {
3823: my ($part,$type) = &split_part_type($apart);
3824: my $score=$record{"resource.$part.$type"};
3825: $result.='<td align="center">';
3826: my ($aggtries,$totaltries);
3827: unless (exists($aggregates{$part})) {
3828: $totaltries = $record{'resource.'.$part.'.tries'};
3829:
3830: $aggtries = $totaltries;
3831: if ($$last_resets{$part}) {
3832: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3833: $part);
3834: }
3835: $result.='<input type="hidden" name="'.
3836: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3837: $result.='<input type="hidden" name="'.
3838: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3839: $aggregates{$part} = 1;
3840: }
3841: if ($type eq 'awarded') {
3842: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3843: $result.='<input type="hidden" name="'.
3844: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3845: $result.='<input type="text" name="'.
3846: 'GD_'.$student.'_'.$part.'_awarded" '.
3847: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3848: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3849: } elsif ($type eq 'solved') {
3850: my ($status,$foo)=split(/_/,$score,2);
3851: $status = 'nothing' if ($status eq '');
3852: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3853: $part.'_solved_s" value="'.$status.'" />'."\n";
3854: $result.=' <select name="'.
3855: 'GD_'.$student.'_'.$part.'_solved" '.
3856: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3857: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3858: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3859: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3860: $result.="</select> </td>\n";
3861: } else {
3862: $result.='<input type="hidden" name="'.
3863: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3864: "\n";
3865: $result.='<input type="text" name="'.
3866: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3867: 'value="'.$score.'" size="4" /></td>'."\n";
3868: }
3869: }
3870: $result.=&Apache::loncommon::end_data_table_row();
3871: return $result;
3872: }
3873:
3874: #--- change scores for all the students in a section/class
3875: # record does not get update if unchanged
3876: sub editgrades {
3877: my ($request) = @_;
3878:
3879: my ($symb)=&get_symb($request);
3880: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3881: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3882: $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
3883: $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
3884:
3885: my $result= &Apache::loncommon::start_data_table().
3886: &Apache::loncommon::start_data_table_header_row().
3887: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3888: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3889: my %scoreptr = (
3890: 'correct' =>'correct_by_override',
3891: 'incorrect'=>'incorrect_by_override',
3892: 'excused' =>'excused',
3893: 'ungraded' =>'ungraded_attempted',
3894: 'credited' =>'credit_attempted',
3895: 'nothing' => '',
3896: );
3897: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3898:
3899: my (@partid);
3900: my %weight = ();
3901: my %columns = ();
3902: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3903:
3904: my $partserror;
3905: my (@parts) = sort(&getpartlist($symb,\$partserror));
3906: if ($partserror) {
3907: return &navmap_errormsg();
3908: }
3909: my $header;
3910: while ($ctr < $env{'form.totalparts'}) {
3911: my $partid = $env{'form.partid_'.$ctr};
3912: push(@partid,$partid);
3913: $weight{$partid} = $env{'form.weight_'.$partid};
3914: $ctr++;
3915: }
3916: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3917: foreach my $partid (@partid) {
3918: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3919: '<th align="center">'.&mt('New Score').'</th>';
3920: $columns{$partid}=2;
3921: foreach my $stores (@parts) {
3922: my ($part,$type) = &split_part_type($stores);
3923: if ($part !~ m/^\Q$partid\E/) { next;}
3924: if ($type eq 'awarded' || $type eq 'solved') { next; }
3925: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3926: $display =~ s/\[Part: \Q$part\E\]//;
3927: my $narrowtext = &mt('Tries');
3928: $display =~ s/Number of Attempts/$narrowtext/;
3929: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3930: '<th align="center">'.&mt('New').' '.$display.'</th>';
3931: $columns{$partid}+=2;
3932: }
3933: }
3934: foreach my $partid (@partid) {
3935: my $display_part=&get_display_part($partid,$symb);
3936: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3937: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3938: '</th>';
3939:
3940: }
3941: $result .= &Apache::loncommon::end_data_table_header_row().
3942: &Apache::loncommon::start_data_table_header_row().
3943: $header.
3944: &Apache::loncommon::end_data_table_header_row();
3945: my @noupdate;
3946: my ($updateCtr,$noupdateCtr) = (1,1);
3947: for ($i=0; $i<$env{'form.total'}; $i++) {
3948: my $line;
3949: my $user = $env{'form.ctr'.$i};
3950: my ($uname,$udom)=split(/:/,$user);
3951: my %newrecord;
3952: my $updateflag = 0;
3953: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3954: my $usec=$classlist->{"$uname:$udom"}[5];
3955: if (!&canmodify($usec)) {
3956: my $numcols=scalar(@partid)*4+2;
3957: push(@noupdate,
3958: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3959: &mt('Not allowed to modify student')."</span></td></tr>");
3960: next;
3961: }
3962: my %aggregate = ();
3963: my $aggregateflag = 0;
3964: $user=~s/:/_/; # colon doen't work in javascript for names
3965: foreach (@partid) {
3966: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3967: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3968: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3969: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3970: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3971: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3972: my $partial = $awarded eq '' ? '' : $pcr;
3973: my $score;
3974: if ($partial eq '') {
3975: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3976: } elsif ($partial > 0) {
3977: $score = 'correct_by_override';
3978: } elsif ($partial == 0) {
3979: $score = 'incorrect_by_override';
3980: }
3981: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3982: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3983:
3984: $newrecord{'resource.'.$_.'.regrader'}=
3985: "$env{'user.name'}:$env{'user.domain'}";
3986: if ($dropMenu eq 'reset status' &&
3987: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3988: $newrecord{'resource.'.$_.'.tries'} = '';
3989: $newrecord{'resource.'.$_.'.solved'} = '';
3990: $newrecord{'resource.'.$_.'.award'} = '';
3991: $newrecord{'resource.'.$_.'.awarded'} = '';
3992: $updateflag = 1;
3993: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3994: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3995: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3996: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3997: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3998: $aggregateflag = 1;
3999: }
4000: } elsif (!($old_part eq $partial && $old_score eq $score)) {
4001: $updateflag = 1;
4002: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
4003: $newrecord{'resource.'.$_.'.solved'} = $score;
4004: $rec_update++;
4005: }
4006:
4007: $line .= '<td align="center">'.$old_aw.' </td>'.
4008: '<td align="center">'.$awarded.
4009: ($score eq 'excused' ? $score : '').' </td>';
4010:
4011:
4012: my $partid=$_;
4013: foreach my $stores (@parts) {
4014: my ($part,$type) = &split_part_type($stores);
4015: if ($part !~ m/^\Q$partid\E/) { next;}
4016: if ($type eq 'awarded' || $type eq 'solved') { next; }
4017: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
4018: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
4019: if ($awarded ne '' && $awarded ne $old_aw) {
4020: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
4021: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
4022: $updateflag=1;
4023: }
4024: $line .= '<td align="center">'.$old_aw.' </td>'.
4025: '<td align="center">'.$awarded.' </td>';
4026: }
4027: }
4028: $line.="\n";
4029:
4030: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4031: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4032:
4033: if ($updateflag) {
4034: $count++;
4035: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
4036: $udom,$uname);
4037:
4038: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
4039: $cnum,$udom,$uname)) {
4040: # need to figure out if should be in queue.
4041: my %record =
4042: &Apache::lonnet::restore($symb,$env{'request.course.id'},
4043: $udom,$uname);
4044: my $all_graded = 1;
4045: my $none_graded = 1;
4046: foreach my $part (@parts) {
4047: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
4048: $all_graded = 0;
4049: } else {
4050: $none_graded = 0;
4051: }
4052: }
4053:
4054: if ($all_graded || $none_graded) {
4055: &Apache::bridgetask::remove_from_queue('gradingqueue',
4056: $symb,$cdom,$cnum,
4057: $udom,$uname);
4058: }
4059: }
4060:
4061: $result.=&Apache::loncommon::start_data_table_row().
4062: '<td align="right"> '.$updateCtr.' </td>'.$line.
4063: &Apache::loncommon::end_data_table_row();
4064: $updateCtr++;
4065: } else {
4066: push(@noupdate,
4067: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4068: $noupdateCtr++;
4069: }
4070: if ($aggregateflag) {
4071: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4072: $cdom,$cnum);
4073: }
4074: }
4075: if (@noupdate) {
4076: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
4077: my $numcols=scalar(@partid)*4+2;
4078: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4079: '<td align="center" colspan="'.$numcols.'">'.
4080: &mt('No Changes Occurred For the Students Below').
4081: '</td>'.
4082: &Apache::loncommon::end_data_table_row();
4083: foreach my $line (@noupdate) {
4084: $result.=
4085: &Apache::loncommon::start_data_table_row().
4086: $line.
4087: &Apache::loncommon::end_data_table_row();
4088: }
4089: }
4090: $result .= &Apache::loncommon::end_data_table().
4091: &show_grading_menu_form($symb);
4092: my $msg = '<p><b>'.
4093: &mt('Number of records updated = [_1] for [quant,_2,student].',
4094: $rec_update,$count).'</b><br />'.
4095: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4096: '</b></p>';
4097: return $title.$msg.$result;
4098: }
4099:
4100: sub split_part_type {
4101: my ($partstr) = @_;
4102: my ($temp,@allparts)=split(/_/,$partstr);
4103: my $type=pop(@allparts);
4104: my $part=join('_',@allparts);
4105: return ($part,$type);
4106: }
4107:
4108: #------------- end of section for handling grading by section/class ---------
4109: #
4110: #----------------------------------------------------------------------------
4111:
4112:
4113: #----------------------------------------------------------------------------
4114: #
4115: #-------------------------- Next few routines handles grading by csv upload
4116: #
4117: #--- Javascript to handle csv upload
4118: sub csvupload_javascript_reverse_associate {
4119: my $error1=&mt('You need to specify the username or the student/employee ID');
4120: my $error2=&mt('You need to specify at least one grading field');
4121: return(<<ENDPICK);
4122: function verify(vf) {
4123: var foundsomething=0;
4124: var founduname=0;
4125: var foundID=0;
4126: for (i=0;i<=vf.nfields.value;i++) {
4127: tw=eval('vf.f'+i+'.selectedIndex');
4128: if (i==0 && tw!=0) { foundID=1; }
4129: if (i==1 && tw!=0) { founduname=1; }
4130: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4131: }
4132: if (founduname==0 && foundID==0) {
4133: alert('$error1');
4134: return;
4135: }
4136: if (foundsomething==0) {
4137: alert('$error2');
4138: return;
4139: }
4140: vf.submit();
4141: }
4142: function flip(vf,tf) {
4143: var nw=eval('vf.f'+tf+'.selectedIndex');
4144: var i;
4145: for (i=0;i<=vf.nfields.value;i++) {
4146: //can not pick the same destination field for both name and domain
4147: if (((i ==0)||(i ==1)) &&
4148: ((tf==0)||(tf==1)) &&
4149: (i!=tf) &&
4150: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4151: eval('vf.f'+i+'.selectedIndex=0;')
4152: }
4153: }
4154: }
4155: ENDPICK
4156: }
4157:
4158: sub csvupload_javascript_forward_associate {
4159: my $error1=&mt('You need to specify the username or the student/employee ID');
4160: my $error2=&mt('You need to specify at least one grading field');
4161: return(<<ENDPICK);
4162: function verify(vf) {
4163: var foundsomething=0;
4164: var founduname=0;
4165: var foundID=0;
4166: for (i=0;i<=vf.nfields.value;i++) {
4167: tw=eval('vf.f'+i+'.selectedIndex');
4168: if (tw==1) { foundID=1; }
4169: if (tw==2) { founduname=1; }
4170: if (tw>3) { foundsomething=1; }
4171: }
4172: if (founduname==0 && foundID==0) {
4173: alert('$error1');
4174: return;
4175: }
4176: if (foundsomething==0) {
4177: alert('$error2');
4178: return;
4179: }
4180: vf.submit();
4181: }
4182: function flip(vf,tf) {
4183: var nw=eval('vf.f'+tf+'.selectedIndex');
4184: var i;
4185: //can not pick the same destination field twice
4186: for (i=0;i<=vf.nfields.value;i++) {
4187: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4188: eval('vf.f'+i+'.selectedIndex=0;')
4189: }
4190: }
4191: }
4192: ENDPICK
4193: }
4194:
4195: sub csvuploadmap_header {
4196: my ($request,$symb,$datatoken,$distotal)= @_;
4197: my $javascript;
4198: if ($env{'form.upfile_associate'} eq 'reverse') {
4199: $javascript=&csvupload_javascript_reverse_associate();
4200: } else {
4201: $javascript=&csvupload_javascript_forward_associate();
4202: }
4203:
4204: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
4205: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
4206: my $ignore=&mt('Ignore First Line');
4207: $symb = &Apache::lonenc::check_encrypt($symb);
4208: $request->print(<<ENDPICK);
4209: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4210: <h3><span class="LC_info">Uploading Class Grades</span></h3>
4211: $result
4212: <hr />
4213: <h3>Identify fields</h3>
4214: Total number of records found in file: $distotal <hr />
4215: Enter as many fields as you can. The system will inform you and bring you back
4216: to this page if the data selected is insufficient to run your class.<hr />
4217: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4218: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
4219: <input type="hidden" name="associate" value="" />
4220: <input type="hidden" name="phase" value="three" />
4221: <input type="hidden" name="datatoken" value="$datatoken" />
4222: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4223: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4224: <input type="hidden" name="upfile_associate"
4225: value="$env{'form.upfile_associate'}" />
4226: <input type="hidden" name="symb" value="$symb" />
4227: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
4228: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
4229: <input type="hidden" name="command" value="csvuploadoptions" />
4230: <hr />
4231: <script type="text/javascript" language="Javascript">
4232: $javascript
4233: </script>
4234: ENDPICK
4235: return '';
4236:
4237: }
4238:
4239: sub csvupload_fields {
4240: my ($symb,$errorref) = @_;
4241: my (@parts) = &getpartlist($symb,$errorref);
4242: if (ref($errorref)) {
4243: if ($$errorref) {
4244: return;
4245: }
4246: }
4247:
4248: my @fields=(['ID','Student/Employee ID'],
4249: ['username','Student Username'],
4250: ['domain','Student Domain']);
4251: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4252: foreach my $part (sort(@parts)) {
4253: my @datum;
4254: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4255: my $name=$part;
4256: if (!$display) { $display = $name; }
4257: @datum=($name,$display);
4258: if ($name=~/^stores_(.*)_awarded/) {
4259: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4260: }
4261: push(@fields,\@datum);
4262: }
4263: return (@fields);
4264: }
4265:
4266: sub csvuploadmap_footer {
4267: my ($request,$i,$keyfields) =@_;
4268: my $buttontext = &mt('Assign Grades');
4269: $request->print(<<ENDPICK);
4270: </table>
4271: <input type="hidden" name="nfields" value="$i" />
4272: <input type="hidden" name="keyfields" value="$keyfields" />
4273: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4274: </form>
4275: ENDPICK
4276: }
4277:
4278: sub checkforfile_js {
4279: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4280: my $result =<<CSVFORMJS;
4281: <script type="text/javascript" language="javascript">
4282: function checkUpload(formname) {
4283: if (formname.upfile.value == "") {
4284: alert("$alertmsg");
4285: return false;
4286: }
4287: formname.submit();
4288: }
4289: </script>
4290: CSVFORMJS
4291: return $result;
4292: }
4293:
4294: sub upcsvScores_form {
4295: my ($request) = shift;
4296: my ($symb)=&get_symb($request);
4297: if (!$symb) {return '';}
4298: my $result=&checkforfile_js();
4299: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
4300: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
4301: $result.=$table;
4302: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
4303: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
4304: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource.').
4305: '</b></td></tr>'."\n";
4306: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
4307: my $upload=&mt("Upload Scores");
4308: my $upfile_select=&Apache::loncommon::upfile_select_html();
4309: my $ignore=&mt('Ignore First Line');
4310: $symb = &Apache::lonenc::check_encrypt($symb);
4311: $result.=<<ENDUPFORM;
4312: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4313: <input type="hidden" name="symb" value="$symb" />
4314: <input type="hidden" name="command" value="csvuploadmap" />
4315: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
4316: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
4317: $upfile_select
4318: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4319: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
4320: </form>
4321: ENDUPFORM
4322: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4323: &mt("How do I create a CSV file from a spreadsheet"))
4324: .'</td></tr></table>'."\n";
4325: $result.='</td></tr></table><br /><br />'."\n";
4326: $result.=&show_grading_menu_form($symb);
4327: return $result;
4328: }
4329:
4330:
4331: sub csvuploadmap {
4332: my ($request)= @_;
4333: my ($symb)=&get_symb($request);
4334: if (!$symb) {return '';}
4335:
4336: my $datatoken;
4337: if (!$env{'form.datatoken'}) {
4338: $datatoken=&Apache::loncommon::upfile_store($request);
4339: } else {
4340: $datatoken=$env{'form.datatoken'};
4341: &Apache::loncommon::load_tmp_file($request);
4342: }
4343: my @records=&Apache::loncommon::upfile_record_sep();
4344: if ($env{'form.noFirstLine'}) { shift(@records); }
4345: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4346: my ($i,$keyfields);
4347: if (@records) {
4348: my $fieldserror;
4349: my @fields=&csvupload_fields($symb,\$fieldserror);
4350: if ($fieldserror) {
4351: $request->print(&navmap_errormsg());
4352: return;
4353: }
4354: if ($env{'form.upfile_associate'} eq 'reverse') {
4355: &Apache::loncommon::csv_print_samples($request,\@records);
4356: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4357: \@fields);
4358: foreach (@fields) { $keyfields.=$_->[0].','; }
4359: chop($keyfields);
4360: } else {
4361: unshift(@fields,['none','']);
4362: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4363: \@fields);
4364: foreach my $rec (@records) {
4365: my %temp = &Apache::loncommon::record_sep($rec);
4366: if (%temp) {
4367: $keyfields=join(',',sort(keys(%temp)));
4368: last;
4369: }
4370: }
4371: }
4372: }
4373: &csvuploadmap_footer($request,$i,$keyfields);
4374: $request->print(&show_grading_menu_form($symb));
4375:
4376: return '';
4377: }
4378:
4379: sub csvuploadoptions {
4380: my ($request)= @_;
4381: my ($symb)=&get_symb($request);
4382: my $checked=(($env{'form.noFirstLine'})?'1':'0');
4383: my $ignore=&mt('Ignore First Line');
4384: $request->print(<<ENDPICK);
4385: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4386: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
4387: <input type="hidden" name="command" value="csvuploadassign" />
4388: <!--
4389: <p>
4390: <label>
4391: <input type="checkbox" name="show_full_results" />
4392: Show a table of all changes
4393: </label>
4394: </p>
4395: -->
4396: <p>
4397: <label>
4398: <input type="checkbox" name="overwite_scores" checked="checked" />
4399: Overwrite any existing score
4400: </label>
4401: </p>
4402: ENDPICK
4403: my %fields=&get_fields();
4404: if (!defined($fields{'domain'})) {
4405: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4406: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
4407: }
4408: foreach my $key (sort(keys(%env))) {
4409: if ($key !~ /^form\.(.*)$/) { next; }
4410: my $cleankey=$1;
4411: if ($cleankey eq 'command') { next; }
4412: $request->print('<input type="hidden" name="'.$cleankey.
4413: '" value="'.$env{$key}.'" />'."\n");
4414: }
4415: # FIXME do a check for any duplicated user ids...
4416: # FIXME do a check for any invalid user ids?...
4417: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4418: <hr /></form>'."\n");
4419: $request->print(&show_grading_menu_form($symb));
4420: return '';
4421: }
4422:
4423: sub get_fields {
4424: my %fields;
4425: my @keyfields = split(/\,/,$env{'form.keyfields'});
4426: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4427: if ($env{'form.upfile_associate'} eq 'reverse') {
4428: if ($env{'form.f'.$i} ne 'none') {
4429: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4430: }
4431: } else {
4432: if ($env{'form.f'.$i} ne 'none') {
4433: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4434: }
4435: }
4436: }
4437: return %fields;
4438: }
4439:
4440: sub csvuploadassign {
4441: my ($request)= @_;
4442: my ($symb)=&get_symb($request);
4443: if (!$symb) {return '';}
4444: my $error_msg = '';
4445: &Apache::loncommon::load_tmp_file($request);
4446: my @gradedata = &Apache::loncommon::upfile_record_sep();
4447: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
4448: my %fields=&get_fields();
4449: $request->print('<h3>Assigning Grades</h3>');
4450: my $courseid=$env{'request.course.id'};
4451: my ($classlist) = &getclasslist('all',0);
4452: my @notallowed;
4453: my @skipped;
4454: my @warnings;
4455: my $countdone=0;
4456: foreach my $grade (@gradedata) {
4457: my %entries=&Apache::loncommon::record_sep($grade);
4458: my $domain;
4459: if ($entries{$fields{'domain'}}) {
4460: $domain=$entries{$fields{'domain'}};
4461: } else {
4462: $domain=$env{'form.default_domain'};
4463: }
4464: $domain=~s/\s//g;
4465: my $username=$entries{$fields{'username'}};
4466: $username=~s/\s//g;
4467: if (!$username) {
4468: my $id=$entries{$fields{'ID'}};
4469: $id=~s/\s//g;
4470: my %ids=&Apache::lonnet::idget($domain,$id);
4471: $username=$ids{$id};
4472: }
4473: if (!exists($$classlist{"$username:$domain"})) {
4474: my $id=$entries{$fields{'ID'}};
4475: $id=~s/\s//g;
4476: if ($id) {
4477: push(@skipped,"$id:$domain");
4478: } else {
4479: push(@skipped,"$username:$domain");
4480: }
4481: next;
4482: }
4483: my $usec=$classlist->{"$username:$domain"}[5];
4484: if (!&canmodify($usec)) {
4485: push(@notallowed,"$username:$domain");
4486: next;
4487: }
4488: my %points;
4489: my %grades;
4490: foreach my $dest (keys(%fields)) {
4491: if ($dest eq 'ID' || $dest eq 'username' ||
4492: $dest eq 'domain') { next; }
4493: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4494: if ($dest=~/stores_(.*)_points/) {
4495: my $part=$1;
4496: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4497: $symb,$domain,$username);
4498: if ($wgt) {
4499: $entries{$fields{$dest}}=~s/\s//g;
4500: my $pcr=$entries{$fields{$dest}} / $wgt;
4501: my $award=($pcr == 0) ? 'incorrect_by_override'
4502: : 'correct_by_override';
4503: if ($pcr>1) {
4504: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4505: }
4506: $grades{"resource.$part.awarded"}=$pcr;
4507: $grades{"resource.$part.solved"}=$award;
4508: $points{$part}=1;
4509: } else {
4510: $error_msg = "<br />" .
4511: &mt("Some point values were assigned"
4512: ." for problems with a weight "
4513: ."of zero. These values were "
4514: ."ignored.");
4515: }
4516: } else {
4517: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4518: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4519: my $store_key=$dest;
4520: $store_key=~s/^stores/resource/;
4521: $store_key=~s/_/\./g;
4522: $grades{$store_key}=$entries{$fields{$dest}};
4523: }
4524: }
4525: if (! %grades) {
4526: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4527: } else {
4528: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4529: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4530: $env{'request.course.id'},
4531: $domain,$username);
4532: if ($result eq 'ok') {
4533: $request->print('.');
4534: # Remove from grading queue
4535: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4536: $env{'course.'.$env{'request.course.id'}.'.domain'},
4537: $env{'course.'.$env{'request.course.id'}.'.num'},
4538: $domain,$username);
4539: } else {
4540: $request->print("<p><span class=\"LC_error\">".
4541: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4542: "$username:$domain",$result)."</span></p>");
4543: }
4544: $request->rflush();
4545: $countdone++;
4546: }
4547: }
4548: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4549: if (@warnings) {
4550: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4551: $request->print(join(', ',@warnings));
4552: }
4553: if (@skipped) {
4554: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4555: $request->print(join(', ',@skipped));
4556: }
4557: if (@notallowed) {
4558: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4559: $request->print(join(', ',@notallowed));
4560: }
4561: $request->print("<br />\n");
4562: $request->print(&show_grading_menu_form($symb));
4563: return $error_msg;
4564: }
4565: #------------- end of section for handling csv file upload ---------
4566: #
4567: #-------------------------------------------------------------------
4568: #
4569: #-------------- Next few routines handle grading by page/sequence
4570: #
4571: #--- Select a page/sequence and a student to grade
4572: sub pickStudentPage {
4573: my ($request) = shift;
4574:
4575: my $alertmsg = &mt('Please select the student you wish to grade.');
4576: $request->print(<<LISTJAVASCRIPT);
4577: <script type="text/javascript" language="javascript">
4578:
4579: function checkPickOne(formname) {
4580: if (radioSelection(formname.student) == null) {
4581: alert("$alertmsg");
4582: return;
4583: }
4584: ptr = pullDownSelection(formname.selectpage);
4585: formname.page.value = formname["page"+ptr].value;
4586: formname.title.value = formname["title"+ptr].value;
4587: formname.submit();
4588: }
4589:
4590: </script>
4591: LISTJAVASCRIPT
4592: &commonJSfunctions($request);
4593: my ($symb) = &get_symb($request);
4594: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4595: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4596: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4597:
4598: my $result='<h3><span class="LC_info"> '.
4599: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4600:
4601: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4602: my $map_error;
4603: my ($titles,$symbx) = &getSymbMap($map_error);
4604: if ($map_error) {
4605: $request->print(&navmap_errormsg());
4606: return;
4607: }
4608: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4609: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4610: # my $type=($curpage =~ /\.(page|sequence)/);
4611: my $select = '<select name="selectpage">'."\n";
4612: my $ctr=0;
4613: foreach (@$titles) {
4614: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4615: $select.='<option value="'.$ctr.'" '.
4616: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4617: '>'.$showtitle.'</option>'."\n";
4618: $ctr++;
4619: }
4620: $select.= '</select>';
4621: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4622:
4623: $ctr=0;
4624: foreach (@$titles) {
4625: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4626: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4627: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4628: $ctr++;
4629: }
4630: $result.='<input type="hidden" name="page" />'."\n".
4631: '<input type="hidden" name="title" />'."\n";
4632:
4633: my $options =
4634: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4635: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4636: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4637:
4638: $options =
4639: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4640: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4641: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4642: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4643:
4644: $result.=&build_section_inputs();
4645: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4646: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4647: '<input type="hidden" name="command" value="displayPage" />'."\n".
4648: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4649: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4650:
4651: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4652:
4653: $result.=' <input type="button" '.
4654: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4655:
4656: $request->print($result);
4657:
4658: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4659: &Apache::loncommon::start_data_table().
4660: &Apache::loncommon::start_data_table_header_row().
4661: '<th align="right"> '.&mt('No.').'</th>'.
4662: '<th>'.&nameUserString('header').'</th>'.
4663: '<th align="right"> '.&mt('No.').'</th>'.
4664: '<th>'.&nameUserString('header').'</th>'.
4665: &Apache::loncommon::end_data_table_header_row();
4666:
4667: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4668: my $ptr = 1;
4669: foreach my $student (sort
4670: {
4671: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4672: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4673: }
4674: return $a cmp $b;
4675: } (keys(%$fullname))) {
4676: my ($uname,$udom) = split(/:/,$student);
4677: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4678: : '</td>');
4679: $studentTable.='<td align="right">'.$ptr.' </td>';
4680: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4681: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4682: $studentTable.=
4683: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4684: : '');
4685: $ptr++;
4686: }
4687: if ($ptr%2 == 0) {
4688: $studentTable.='</td><td> </td><td> </td>'.
4689: &Apache::loncommon::end_data_table_row();
4690: }
4691: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4692: $studentTable.='<input type="button" '.
4693: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4694:
4695: $studentTable.=&show_grading_menu_form($symb);
4696: $request->print($studentTable);
4697:
4698: return '';
4699: }
4700:
4701: sub getSymbMap {
4702: my ($map_error) = @_;
4703: my $navmap = Apache::lonnavmaps::navmap->new();
4704: unless (ref($navmap)) {
4705: if (ref($map_error)) {
4706: $$map_error = 'navmap';
4707: }
4708: return;
4709: }
4710: my %symbx = ();
4711: my @titles = ();
4712: my $minder = 0;
4713:
4714: # Gather every sequence that has problems.
4715: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4716: 1,0,1);
4717: for my $sequence ($navmap->getById('0.0'), @sequences) {
4718: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4719: my $title = $minder.'.'.
4720: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4721: push(@titles, $title); # minder in case two titles are identical
4722: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4723: $minder++;
4724: }
4725: }
4726: return \@titles,\%symbx;
4727: }
4728:
4729: #
4730: #--- Displays a page/sequence w/wo problems, w/wo submissions
4731: sub displayPage {
4732: my ($request) = shift;
4733:
4734: my ($symb) = &get_symb($request);
4735: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4736: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4737: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4738: my $pageTitle = $env{'form.page'};
4739: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4740: my ($uname,$udom) = split(/:/,$env{'form.student'});
4741: my $usec=$classlist->{$env{'form.student'}}[5];
4742:
4743: #need to make sure we have the correct data for later EXT calls,
4744: #thus invalidate the cache
4745: &Apache::lonnet::devalidatecourseresdata(
4746: $env{'course.'.$env{'request.course.id'}.'.num'},
4747: $env{'course.'.$env{'request.course.id'}.'.domain'});
4748: &Apache::lonnet::clear_EXT_cache_status();
4749:
4750: if (!&canview($usec)) {
4751: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4752: $request->print(&show_grading_menu_form($symb));
4753: return;
4754: }
4755: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4756: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4757: '</h3>'."\n";
4758: $env{'form.CODE'} = uc($env{'form.CODE'});
4759: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4760: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4761: } else {
4762: delete($env{'form.CODE'});
4763: }
4764: &sub_page_js($request);
4765: $request->print($result);
4766:
4767: my $navmap = Apache::lonnavmaps::navmap->new();
4768: unless (ref($navmap)) {
4769: $request->print(&navmap_errormsg());
4770: $request->print(&show_grading_menu_form($symb));
4771: return;
4772: }
4773: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4774: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4775: if (!$map) {
4776: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4777: $request->print(&show_grading_menu_form($symb));
4778: return;
4779: }
4780: my $iterator = $navmap->getIterator($map->map_start(),
4781: $map->map_finish());
4782:
4783: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4784: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4785: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4786: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4787: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4788: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4789: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4790: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4791: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4792:
4793: if (defined($env{'form.CODE'})) {
4794: $studentTable.=
4795: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4796: }
4797: my $checkIcon = '<img alt="'.&mt('Check Mark').
4798: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4799:
4800: $studentTable.=' <span class="LC_info">'.
4801: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4802: '</span>'."\n".
4803: &Apache::loncommon::start_data_table().
4804: &Apache::loncommon::start_data_table_header_row().
4805: '<th align="center"> Prob. </th>'.
4806: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4807: &Apache::loncommon::end_data_table_header_row();
4808:
4809: &Apache::lonxml::clear_problem_counter();
4810: my ($depth,$question,$prob) = (1,1,1);
4811: $iterator->next(); # skip the first BEGIN_MAP
4812: my $curRes = $iterator->next(); # for "current resource"
4813: while ($depth > 0) {
4814: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4815: if($curRes == $iterator->END_MAP) { $depth--; }
4816:
4817: if (ref($curRes) && $curRes->is_problem()) {
4818: my $parts = $curRes->parts();
4819: my $title = $curRes->compTitle();
4820: my $symbx = $curRes->symb();
4821: $studentTable.=
4822: &Apache::loncommon::start_data_table_row().
4823: '<td align="center" valign="top" >'.$prob.
4824: (scalar(@{$parts}) == 1 ? ''
4825: : '<br />('.&mt('[_1]parts',
4826: scalar(@{$parts}).' ').')'
4827: ).
4828: '</td>';
4829: $studentTable.='<td valign="top">';
4830: my %form = ('CODE' => $env{'form.CODE'},);
4831: if ($env{'form.vProb'} eq 'yes' ) {
4832: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4833: undef,'both',\%form);
4834: } else {
4835: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4836: $companswer =~ s|<form(.*?)>||g;
4837: $companswer =~ s|</form>||g;
4838: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4839: # $companswer =~ s/$1/ /ms;
4840: # $request->print('match='.$1."<br />\n");
4841: # }
4842: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4843: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4844: }
4845:
4846: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4847:
4848: if ($env{'form.lastSub'} eq 'datesub') {
4849: if ($record{'version'} eq '') {
4850: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4851: } else {
4852: my %responseType = ();
4853: foreach my $partid (@{$parts}) {
4854: my @responseIds =$curRes->responseIds($partid);
4855: my @responseType =$curRes->responseType($partid);
4856: my %responseIds;
4857: for (my $i=0;$i<=$#responseIds;$i++) {
4858: $responseIds{$responseIds[$i]}=$responseType[$i];
4859: }
4860: $responseType{$partid} = \%responseIds;
4861: }
4862: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4863:
4864: }
4865: } elsif ($env{'form.lastSub'} eq 'all') {
4866: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4867: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4868: $env{'request.course.id'},
4869: '','.submission');
4870:
4871: }
4872: if (&canmodify($usec)) {
4873: $studentTable.=&gradeBox_start();
4874: foreach my $partid (@{$parts}) {
4875: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4876: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4877: $question++;
4878: }
4879: $studentTable.=&gradeBox_end();
4880: $prob++;
4881: }
4882: $studentTable.='</td></tr>';
4883:
4884: }
4885: $curRes = $iterator->next();
4886: }
4887:
4888: $studentTable.=
4889: '</table>'."\n".
4890: '<input type="button" value="'.&mt('Save').'" '.
4891: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4892: '</form>'."\n";
4893: $studentTable.=&show_grading_menu_form($symb);
4894: $request->print($studentTable);
4895:
4896: return '';
4897: }
4898:
4899: sub displaySubByDates {
4900: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4901: my $isCODE=0;
4902: my $isTask = ($symb =~/\.task$/);
4903: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4904: my $studentTable=&Apache::loncommon::start_data_table().
4905: &Apache::loncommon::start_data_table_header_row().
4906: '<th>'.&mt('Date/Time').'</th>'.
4907: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4908: ($isTask?'<th>'.&mt('Version').'</th>':'').
4909: '<th>'.&mt('Submission').'</th>'.
4910: '<th>'.&mt('Status').'</th>'.
4911: &Apache::loncommon::end_data_table_header_row();
4912: my ($version);
4913: my %mark;
4914: my %orders;
4915: $mark{'correct_by_student'} = $checkIcon;
4916: if (!exists($$record{'1:timestamp'})) {
4917: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4918: }
4919:
4920: my $interaction;
4921: my $no_increment = 1;
4922: my %lastrndseed;
4923: for ($version=1;$version<=$$record{'version'};$version++) {
4924: my $timestamp =
4925: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4926: if (exists($$record{$version.':resource.0.version'})) {
4927: $interaction = $$record{$version.':resource.0.version'};
4928: }
4929: if ($isTask && $env{'form.previousversion'}) {
4930: next unless ($interaction == $env{'form.previousversion'});
4931: }
4932: my $where = ($isTask ? "$version:resource.$interaction"
4933: : "$version:resource");
4934: $studentTable.=&Apache::loncommon::start_data_table_row().
4935: '<td>'.$timestamp.'</td>';
4936: if ($isCODE) {
4937: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4938: }
4939: if ($isTask) {
4940: $studentTable.='<td>'.$interaction.'</td>';
4941: }
4942: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4943: my @displaySub = ();
4944: foreach my $partid (@{$parts}) {
4945: my ($hidden,$type);
4946: $type = $$record{$version.':resource.'.$partid.'.type'};
4947: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4948: $hidden = 1;
4949: }
4950: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4951: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4952:
4953: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4954: my $display_part=&get_display_part($partid,$symb);
4955: foreach my $matchKey (@matchKey) {
4956: if (exists($$record{$version.':'.$matchKey}) &&
4957: $$record{$version.':'.$matchKey} ne '') {
4958:
4959: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4960: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4961: $displaySub[0].='<span class="LC_nobreak">';
4962: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4963: .' <span class="LC_internal_info">'
4964: .'('.&mt('Response ID: [_1]',$responseId).')'
4965: .'</span>'
4966: .' <b>';
4967: if ($hidden) {
4968: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4969: } else {
4970: my ($trial,$rndseed,$newvariation);
4971: if ($type eq 'randomizetry') {
4972: $trial = $$record{"$where.$partid.tries"};
4973: $rndseed = $$record{"$where.$partid.rndseed"};
4974: }
4975: if ($$record{"$where.$partid.tries"} eq '') {
4976: $displaySub[0].=&mt('Trial not counted');
4977: } else {
4978: $displaySub[0].=&mt('Trial: [_1]',
4979: $$record{"$where.$partid.tries"});
4980: if ($rndseed || $lastrndseed{$partid}) {
4981: if ($rndseed ne $lastrndseed{$partid}) {
4982: $newvariation = ' ('.&mt('New variation this try').')';
4983: }
4984: }
4985: }
4986: my $responseType=($isTask ? 'Task'
4987: : $responseType->{$partid}->{$responseId});
4988: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4989: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4990: $orders{$partid}->{$responseId}=
4991: &get_order($partid,$responseId,$symb,$uname,$udom,
4992: $no_increment,$type,$trial,$rndseed);
4993: }
4994: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4995: $displaySub[0].=' '.
4996: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4997: }
4998: }
4999: }
5000: if (exists($$record{"$where.$partid.checkedin"})) {
5001: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
5002: $$record{"$where.$partid.checkedin"},
5003: $$record{"$where.$partid.checkedin.slot"}).
5004: '<br />';
5005: }
5006: if (exists $$record{"$where.$partid.award"}) {
5007: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
5008: lc($$record{"$where.$partid.award"}).' '.
5009: $mark{$$record{"$where.$partid.solved"}}.
5010: '<br />';
5011: }
5012: if (exists $$record{"$where.$partid.regrader"}) {
5013: $displaySub[2].=$$record{"$where.$partid.regrader"}.
5014: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5015: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
5016: $displaySub[2].=
5017: $$record{"$version:resource.$partid.regrader"}.
5018: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5019: }
5020: }
5021: # needed because old essay regrader has not parts info
5022: if (exists $$record{"$version:resource.regrader"}) {
5023: $displaySub[2].=$$record{"$version:resource.regrader"};
5024: }
5025: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
5026: if ($displaySub[2]) {
5027: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
5028: }
5029: $studentTable.=' </td>'.
5030: &Apache::loncommon::end_data_table_row();
5031: }
5032: $studentTable.=&Apache::loncommon::end_data_table();
5033: return $studentTable;
5034: }
5035:
5036: sub updateGradeByPage {
5037: my ($request) = shift;
5038:
5039: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5040: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5041: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5042: my $pageTitle = $env{'form.page'};
5043: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5044: my ($uname,$udom) = split(/:/,$env{'form.student'});
5045: my $usec=$classlist->{$env{'form.student'}}[5];
5046: if (!&canmodify($usec)) {
5047: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
5048: $request->print(&show_grading_menu_form($env{'form.symb'}));
5049: return;
5050: }
5051: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5052: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
5053: '</h3>'."\n";
5054:
5055: $request->print($result);
5056:
5057:
5058: my $navmap = Apache::lonnavmaps::navmap->new();
5059: unless (ref($navmap)) {
5060: $request->print(&navmap_errormsg());
5061: return;
5062: }
5063: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
5064: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5065: if (!$map) {
5066: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
5067: my ($symb)=&get_symb($request);
5068: $request->print(&show_grading_menu_form($symb));
5069: return;
5070: }
5071: my $iterator = $navmap->getIterator($map->map_start(),
5072: $map->map_finish());
5073:
5074: my $studentTable=
5075: &Apache::loncommon::start_data_table().
5076: &Apache::loncommon::start_data_table_header_row().
5077: '<th align="center"> '.&mt('Prob.').' </th>'.
5078: '<th> '.&mt('Title').' </th>'.
5079: '<th> '.&mt('Previous Score').' </th>'.
5080: '<th> '.&mt('New Score').' </th>'.
5081: &Apache::loncommon::end_data_table_header_row();
5082:
5083: $iterator->next(); # skip the first BEGIN_MAP
5084: my $curRes = $iterator->next(); # for "current resource"
5085: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
5086: while ($depth > 0) {
5087: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5088: if($curRes == $iterator->END_MAP) { $depth--; }
5089:
5090: if (ref($curRes) && $curRes->is_problem()) {
5091: my $parts = $curRes->parts();
5092: my $title = $curRes->compTitle();
5093: my $symbx = $curRes->symb();
5094: $studentTable.=
5095: &Apache::loncommon::start_data_table_row().
5096: '<td align="center" valign="top" >'.$prob.
5097: (scalar(@{$parts}) == 1 ? ''
5098: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5099: .')').'</td>';
5100: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5101:
5102: my %newrecord=();
5103: my @displayPts=();
5104: my %aggregate = ();
5105: my $aggregateflag = 0;
5106: foreach my $partid (@{$parts}) {
5107: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5108: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5109:
5110: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5111: $env{'form.WGT'.$question.'_'.$partid} : 1;
5112: my $partial = $newpts/$wgt;
5113: my $score;
5114: if ($partial > 0) {
5115: $score = 'correct_by_override';
5116: } elsif ($newpts ne '') { #empty is taken as 0
5117: $score = 'incorrect_by_override';
5118: }
5119: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5120: if ($dropMenu eq 'excused') {
5121: $partial = '';
5122: $score = 'excused';
5123: } elsif ($dropMenu eq 'reset status'
5124: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5125: $newrecord{'resource.'.$partid.'.tries'} = 0;
5126: $newrecord{'resource.'.$partid.'.solved'} = '';
5127: $newrecord{'resource.'.$partid.'.award'} = '';
5128: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5129: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5130: $changeflag++;
5131: $newpts = '';
5132:
5133: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5134: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5135: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5136: if ($aggtries > 0) {
5137: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5138: $aggregateflag = 1;
5139: }
5140: }
5141: my $display_part=&get_display_part($partid,$curRes->symb());
5142: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5143: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5144: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5145: ' <br />';
5146: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5147: (($score eq 'excused') ? 'excused' : $newpts).
5148: ' <br />';
5149: $question++;
5150: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5151:
5152: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5153: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5154: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5155: if (scalar(keys(%newrecord)) > 0);
5156:
5157: $changeflag++;
5158: }
5159: if (scalar(keys(%newrecord)) > 0) {
5160: my %record =
5161: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5162: $udom,$uname);
5163:
5164: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5165: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5166: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5167: $newrecord{'resource.CODE'} = '';
5168: }
5169: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5170: $udom,$uname);
5171: %record = &Apache::lonnet::restore($symbx,
5172: $env{'request.course.id'},
5173: $udom,$uname);
5174: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5175: $cdom,$cnum,$udom,$uname);
5176: }
5177:
5178: if ($aggregateflag) {
5179: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5180: $env{'course.'.$env{'request.course.id'}.'.domain'},
5181: $env{'course.'.$env{'request.course.id'}.'.num'});
5182: }
5183:
5184: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5185: '<td valign="top">'.$displayPts[1].'</td>'.
5186: &Apache::loncommon::end_data_table_row();
5187:
5188: $prob++;
5189: }
5190: $curRes = $iterator->next();
5191: }
5192:
5193: $studentTable.=&Apache::loncommon::end_data_table();
5194: $studentTable.=&show_grading_menu_form($env{'form.symb'});
5195: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5196: &mt('The scores were changed for [quant,_1,problem].',
5197: $changeflag));
5198: $request->print($grademsg.$studentTable);
5199:
5200: return '';
5201: }
5202:
5203: #-------- end of section for handling grading by page/sequence ---------
5204: #
5205: #-------------------------------------------------------------------
5206:
5207: #-------------------- Bubblesheet (Scantron) Grading -------------------
5208: #
5209: #------ start of section for handling grading by page/sequence ---------
5210:
5211: =pod
5212:
5213: =head1 Bubble sheet grading routines
5214:
5215: For this documentation:
5216:
5217: 'scanline' refers to the full line of characters
5218: from the file that we are parsing that represents one entire sheet
5219:
5220: 'bubble line' refers to the data
5221: representing the line of bubbles that are on the physical bubblesheet
5222:
5223:
5224: The overall process is that a scanned in bubblesheet data is uploaded
5225: into a course. When a user wants to grade, they select a
5226: sequence/folder of resources, a file of bubblesheet info, and pick
5227: one of the predefined configurations for what each scanline looks
5228: like.
5229:
5230: Next each scanline is checked for any errors of either 'missing
5231: bubbles' (it's an error because it may have been mis-scanned
5232: because too light bubbling), 'double bubble' (each bubble line should
5233: have no more than one letter picked), invalid or duplicated CODE,
5234: invalid student/employee ID
5235:
5236: If the CODE option is used that determines the randomization of the
5237: homework problems, either way the student/employee ID is looked up into a
5238: username:domain.
5239:
5240: During the validation phase the instructor can choose to skip scanlines.
5241:
5242: After the validation phase, there are now 3 bubblesheet files
5243:
5244: scantron_original_filename (unmodified original file)
5245: scantron_corrected_filename (file where the corrected information has replaced the original information)
5246: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5247:
5248: Also there is a separate hash nohist_scantrondata that contains extra
5249: correction information that isn't representable in the bubblesheet
5250: file (see &scantron_getfile() for more information)
5251:
5252: After all scanlines are either valid, marked as valid or skipped, then
5253: foreach line foreach problem in the picked sequence, an ssi request is
5254: made that simulates a user submitting their selected letter(s) against
5255: the homework problem.
5256:
5257: =over 4
5258:
5259:
5260:
5261: =item defaultFormData
5262:
5263: Returns html hidden inputs used to hold context/default values.
5264:
5265: Arguments:
5266: $symb - $symb of the current resource
5267:
5268: =cut
5269:
5270: sub defaultFormData {
5271: my ($symb)=@_;
5272: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
5273: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
5274: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
5275: }
5276:
5277:
5278: =pod
5279:
5280: =item getSequenceDropDown
5281:
5282: Return html dropdown of possible sequences to grade
5283:
5284: Arguments:
5285: $symb - $symb of the current resource
5286: $map_error - ref to scalar which will container error if
5287: $navmap object is unavailable in &getSymbMap().
5288:
5289: =cut
5290:
5291: sub getSequenceDropDown {
5292: my ($symb,$map_error)=@_;
5293: my $result='<select name="selectpage">'."\n";
5294: my ($titles,$symbx) = &getSymbMap($map_error);
5295: if (ref($map_error)) {
5296: return if ($$map_error);
5297: }
5298: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5299: my $ctr=0;
5300: foreach (@$titles) {
5301: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5302: $result.='<option value="'.$$symbx{$_}.'" '.
5303: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5304: '>'.$showtitle.'</option>'."\n";
5305: $ctr++;
5306: }
5307: $result.= '</select>';
5308: return $result;
5309: }
5310:
5311: my %bubble_lines_per_response; # no. bubble lines for each response.
5312: # key is zero-based index - 0, 1, 2 ...
5313:
5314: my %first_bubble_line; # First bubble line no. for each bubble.
5315:
5316: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5317: # matchresponse or rankresponse, where
5318: # an individual response can have multiple
5319: # lines
5320:
5321: my %responsetype_per_response; # responsetype for each response
5322:
5323: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5324: # numbered response. Needed when randomorder
5325: # or randompick are in use. Key is ID, value
5326: # is response number.
5327:
5328: # Save and restore the bubble lines array to the form env.
5329:
5330:
5331: sub save_bubble_lines {
5332: foreach my $line (keys(%bubble_lines_per_response)) {
5333: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5334: $env{"form.scantron.first_bubble_line.$line"} =
5335: $first_bubble_line{$line};
5336: $env{"form.scantron.sub_bubblelines.$line"} =
5337: $subdivided_bubble_lines{$line};
5338: $env{"form.scantron.responsetype.$line"} =
5339: $responsetype_per_response{$line};
5340: }
5341: foreach my $resid (keys(%masterseq_id_responsenum)) {
5342: my $line = $masterseq_id_responsenum{$resid};
5343: $env{"form.scantron.residpart.$line"} = $resid;
5344: }
5345: }
5346:
5347:
5348: sub restore_bubble_lines {
5349: my $line = 0;
5350: %bubble_lines_per_response = ();
5351: %masterseq_id_responsenum = ();
5352: while ($env{"form.scantron.bubblelines.$line"}) {
5353: my $value = $env{"form.scantron.bubblelines.$line"};
5354: $bubble_lines_per_response{$line} = $value;
5355: $first_bubble_line{$line} =
5356: $env{"form.scantron.first_bubble_line.$line"};
5357: $subdivided_bubble_lines{$line} =
5358: $env{"form.scantron.sub_bubblelines.$line"};
5359: $responsetype_per_response{$line} =
5360: $env{"form.scantron.responsetype.$line"};
5361: my $id = $env{"form.scantron.residpart.$line"};
5362: $masterseq_id_responsenum{$id} = $line;
5363: $line++;
5364: }
5365: }
5366:
5367: =pod
5368:
5369: =item scantron_filenames
5370:
5371: Returns a list of the scantron files in the current course
5372:
5373: =cut
5374:
5375: sub scantron_filenames {
5376: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5377: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5378: my $getpropath = 1;
5379: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5380: $cname,$getpropath);
5381: my @possiblenames;
5382: if (ref($dirlist) eq 'ARRAY') {
5383: foreach my $filename (sort(@{$dirlist})) {
5384: ($filename)=split(/&/,$filename);
5385: if ($filename!~/^scantron_orig_/) { next ; }
5386: $filename=~s/^scantron_orig_//;
5387: push(@possiblenames,$filename);
5388: }
5389: }
5390: return @possiblenames;
5391: }
5392:
5393: =pod
5394:
5395: =item scantron_uploads
5396:
5397: Returns html drop-down list of scantron files in current course.
5398:
5399: Arguments:
5400: $file2grade - filename to set as selected in the dropdown
5401:
5402: =cut
5403:
5404: sub scantron_uploads {
5405: my ($file2grade) = @_;
5406: my $result= '<select name="scantron_selectfile">';
5407: $result.="<option></option>";
5408: foreach my $filename (sort(&scantron_filenames())) {
5409: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5410: }
5411: $result.="</select>";
5412: return $result;
5413: }
5414:
5415: =pod
5416:
5417: =item scantron_scantab
5418:
5419: Returns html drop down of the scantron formats in the scantronformat.tab
5420: file.
5421:
5422: =cut
5423:
5424: sub scantron_scantab {
5425: my $result='<select name="scantron_format">'."\n";
5426: $result.='<option></option>'."\n";
5427: my @lines = &get_scantronformat_file();
5428: if (@lines > 0) {
5429: foreach my $line (@lines) {
5430: next if (($line =~ /^\#/) || ($line eq ''));
5431: my ($name,$descrip)=split(/:/,$line);
5432: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5433: }
5434: }
5435: $result.='</select>'."\n";
5436: return $result;
5437: }
5438:
5439: =pod
5440:
5441: =item get_scantronformat_file
5442:
5443: Returns an array containing lines from the scantron format file for
5444: the domain of the course.
5445:
5446: If a url for a custom.tab file is listed in domain's configuration.db,
5447: lines are from this file.
5448:
5449: Otherwise, if a default.tab has been published in RES space by the
5450: domainconfig user, lines are from this file.
5451:
5452: Otherwise, fall back to getting lines from the legacy file on the
5453: local server: /home/httpd/lonTabs/default_scantronformat.tab
5454:
5455: =cut
5456:
5457: sub get_scantronformat_file {
5458: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5459: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5460: my $gottab = 0;
5461: my @lines;
5462: if (ref($domconfig{'scantron'}) eq 'HASH') {
5463: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5464: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5465: if ($formatfile ne '-1') {
5466: @lines = split("\n",$formatfile,-1);
5467: $gottab = 1;
5468: }
5469: }
5470: }
5471: if (!$gottab) {
5472: my $confname = $cdom.'-domainconfig';
5473: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5474: my $formatfile = &Apache::lonnet::getfile($default);
5475: if ($formatfile ne '-1') {
5476: @lines = split("\n",$formatfile,-1);
5477: $gottab = 1;
5478: }
5479: }
5480: if (!$gottab) {
5481: my @domains = &Apache::lonnet::current_machine_domains();
5482: if (grep(/^\Q$cdom\E$/,@domains)) {
5483: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5484: @lines = <$fh>;
5485: close($fh);
5486: } else {
5487: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5488: @lines = <$fh>;
5489: close($fh);
5490: }
5491: }
5492: return @lines;
5493: }
5494:
5495: =pod
5496:
5497: =item scantron_CODElist
5498:
5499: Returns html drop down of the saved CODE lists from current course,
5500: generated from earlier printings.
5501:
5502: =cut
5503:
5504: sub scantron_CODElist {
5505: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5506: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5507: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5508: my $namechoice='<option></option>';
5509: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5510: if ($name =~ /^error: 2 /) { next; }
5511: if ($name =~ /^type\0/) { next; }
5512: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5513: }
5514: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5515: return $namechoice;
5516: }
5517:
5518: =pod
5519:
5520: =item scantron_CODEunique
5521:
5522: Returns the html for "Each CODE to be used once" radio.
5523:
5524: =cut
5525:
5526: sub scantron_CODEunique {
5527: my $result='<span class="LC_nobreak">
5528: <label><input type="radio" name="scantron_CODEunique"
5529: value="yes" checked="checked" />'.&mt('Yes').' </label>
5530: </span>
5531: <span class="LC_nobreak">
5532: <label><input type="radio" name="scantron_CODEunique"
5533: value="no" />'.&mt('No').' </label>
5534: </span>';
5535: return $result;
5536: }
5537:
5538: =pod
5539:
5540: =item scantron_selectphase
5541:
5542: Generates the initial screen to start the bubblesheet process.
5543: Allows for - starting a grading run.
5544: - downloading existing scan data (original, corrected
5545: or skipped info)
5546:
5547: - uploading new scan data
5548:
5549: Arguments:
5550: $r - The Apache request object
5551: $file2grade - name of the file that contain the scanned data to score
5552:
5553: =cut
5554:
5555: sub scantron_selectphase {
5556: my ($r,$file2grade) = @_;
5557: my ($symb)=&get_symb($r);
5558: if (!$symb) {return '';}
5559: my $map_error;
5560: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5561: if ($map_error) {
5562: $r->print('<br />'.&navmap_errormsg().'<br />');
5563: return;
5564: }
5565: my $default_form_data=&defaultFormData($symb);
5566: my $grading_menu_button=&show_grading_menu_form($symb);
5567: my $file_selector=&scantron_uploads($file2grade);
5568: my $format_selector=&scantron_scantab();
5569: my $CODE_selector=&scantron_CODElist();
5570: my $CODE_unique=&scantron_CODEunique();
5571: my $result;
5572:
5573: $ssi_error = 0;
5574:
5575: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5576: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5577:
5578: # Chunk of form to prompt for a scantron file upload.
5579:
5580: $r->print('
5581: <br />
5582: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5583: '.&Apache::loncommon::start_data_table_header_row().'
5584: <th>
5585: '.&mt('Specify a bubblesheet data file to upload.').'
5586: </th>
5587: '.&Apache::loncommon::end_data_table_header_row().'
5588: '.&Apache::loncommon::start_data_table_row().'
5589: <td>
5590: ');
5591: my $default_form_data=&defaultFormData(&get_symb($r,1));
5592: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5593: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5594: $r->print('
5595: <script type="text/javascript" language="javascript">
5596: function checkUpload(formname) {
5597: if (formname.upfile.value == "") {
5598: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5599: return false;
5600: }
5601: formname.submit();
5602: }
5603: </script>
5604:
5605: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5606: '.$default_form_data.'
5607: <input name="courseid" type="hidden" value="'.$cnum.'" />
5608: <input name="domainid" type="hidden" value="'.$cdom.'" />
5609: <input name="command" value="scantronupload_save" type="hidden" />
5610: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5611: <br />
5612: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5613: </form>
5614: ');
5615:
5616: $r->print('
5617: </td>
5618: '.&Apache::loncommon::end_data_table_row().'
5619: '.&Apache::loncommon::end_data_table().'
5620: ');
5621: }
5622:
5623: # Chunk of form to prompt for a file to grade and how:
5624:
5625: $result.= '
5626: <br />
5627: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5628: <input type="hidden" name="command" value="scantron_warning" />
5629: '.$default_form_data.'
5630: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5631: '.&Apache::loncommon::start_data_table_header_row().'
5632: <th colspan="2">
5633: '.&mt('Specify file and which Folder/Sequence to grade').'
5634: </th>
5635: '.&Apache::loncommon::end_data_table_header_row().'
5636: '.&Apache::loncommon::start_data_table_row().'
5637: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5638: '.&Apache::loncommon::end_data_table_row().'
5639: '.&Apache::loncommon::start_data_table_row().'
5640: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5641: '.&Apache::loncommon::end_data_table_row().'
5642: '.&Apache::loncommon::start_data_table_row().'
5643: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5644: '.&Apache::loncommon::end_data_table_row().'
5645: '.&Apache::loncommon::start_data_table_row().'
5646: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5647: '.&Apache::loncommon::end_data_table_row().'
5648: '.&Apache::loncommon::start_data_table_row().'
5649: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5650: '.&Apache::loncommon::end_data_table_row().'
5651: '.&Apache::loncommon::start_data_table_row().'
5652: <td> '.&mt('Options:').' </td>
5653: <td>
5654: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5655: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5656: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5657: </td>
5658: '.&Apache::loncommon::end_data_table_row().'
5659: '.&Apache::loncommon::start_data_table_row().'
5660: <td colspan="2">
5661: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5662: </td>
5663: '.&Apache::loncommon::end_data_table_row().'
5664: '.&Apache::loncommon::end_data_table().'
5665: </form>
5666: ';
5667:
5668: $r->print($result);
5669:
5670: # Chunk of the form that prompts to view a scoring office file,
5671: # corrected file, skipped records in a file.
5672:
5673: $r->print('
5674: <br />
5675: <form action="/adm/grades" name="scantron_download">
5676: '.$default_form_data.'
5677: <input type="hidden" name="command" value="scantron_download" />
5678: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5679: '.&Apache::loncommon::start_data_table_header_row().'
5680: <th>
5681: '.&mt('Download a scoring office file').'
5682: </th>
5683: '.&Apache::loncommon::end_data_table_header_row().'
5684: '.&Apache::loncommon::start_data_table_row().'
5685: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5686: <br />
5687: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5688: '.&Apache::loncommon::end_data_table_row().'
5689: '.&Apache::loncommon::end_data_table().'
5690: </form>
5691: <br />
5692: ');
5693:
5694: &Apache::lonpickcode::code_list($r,2);
5695:
5696: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5697: $default_form_data."\n".
5698: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5699: &Apache::loncommon::start_data_table_header_row()."\n".
5700: '<th colspan="2">
5701: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5702: '</th>'."\n".
5703: &Apache::loncommon::end_data_table_header_row()."\n".
5704: &Apache::loncommon::start_data_table_row()."\n".
5705: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5706: '<td> '.$sequence_selector.' </td>'.
5707: &Apache::loncommon::end_data_table_row()."\n".
5708: &Apache::loncommon::start_data_table_row()."\n".
5709: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5710: '<td> '.$file_selector.' </td>'."\n".
5711: &Apache::loncommon::end_data_table_row()."\n".
5712: &Apache::loncommon::start_data_table_row()."\n".
5713: '<td> '.&mt('Format of data file:').' </td>'."\n".
5714: '<td> '.$format_selector.' </td>'."\n".
5715: &Apache::loncommon::end_data_table_row()."\n".
5716: &Apache::loncommon::start_data_table_row()."\n".
5717: '<td> '.&mt('Options').' </td>'."\n".
5718: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5719: &Apache::loncommon::end_data_table_row()."\n".
5720: &Apache::loncommon::start_data_table_row()."\n".
5721: '<td colspan="2">'."\n".
5722: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5723: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5724: '</td>'."\n".
5725: &Apache::loncommon::end_data_table_row()."\n".
5726: &Apache::loncommon::end_data_table()."\n".
5727: '</form><br />');
5728: $r->print($grading_menu_button);
5729: return;
5730: }
5731:
5732: =pod
5733:
5734: =item get_scantron_config
5735:
5736: Parse and return the scantron configuration line selected as a
5737: hash of configuration file fields.
5738:
5739: Arguments:
5740: which - the name of the configuration to parse from the file.
5741:
5742:
5743: Returns:
5744: If the named configuration is not in the file, an empty
5745: hash is returned.
5746: a hash with the fields
5747: name - internal name for the this configuration setup
5748: description - text to display to operator that describes this config
5749: CODElocation - if 0 or the string 'none'
5750: - no CODE exists for this config
5751: if -1 || the string 'letter'
5752: - a CODE exists for this config and is
5753: a string of letters
5754: Unsupported value (but planned for future support)
5755: if a positive integer
5756: - The CODE exists as the first n items from
5757: the question section of the form
5758: if the string 'number'
5759: - The CODE exists for this config and is
5760: a string of numbers
5761: CODEstart - (only matter if a CODE exists) column in the line where
5762: the CODE starts
5763: CODElength - length of the CODE
5764: IDstart - column where the student/employee ID starts
5765: IDlength - length of the student/employee ID info
5766: Qstart - column where the information from the bubbled
5767: 'questions' start
5768: Qlength - number of columns comprising a single bubble line from
5769: the sheet. (usually either 1 or 10)
5770: Qon - either a single character representing the character used
5771: to signal a bubble was chosen in the positional setup, or
5772: the string 'letter' if the letter of the chosen bubble is
5773: in the final, or 'number' if a number representing the
5774: chosen bubble is in the file (1->A 0->J)
5775: Qoff - the character used to represent that a bubble was
5776: left blank
5777: PaperID - if the scanning process generates a unique number for each
5778: sheet scanned the column that this ID number starts in
5779: PaperIDlength - number of columns that comprise the unique ID number
5780: for the sheet of paper
5781: FirstName - column that the first name starts in
5782: FirstNameLength - number of columns that the first name spans
5783:
5784: LastName - column that the last name starts in
5785: LastNameLength - number of columns that the last name spans
5786: BubblesPerRow - number of bubbles available in each row used to
5787: bubble an answer. (If not specified, 10 assumed).
5788:
5789: =cut
5790:
5791: sub get_scantron_config {
5792: my ($which) = @_;
5793: my @lines = &get_scantronformat_file();
5794: my %config;
5795: #FIXME probably should move to XML it has already gotten a bit much now
5796: foreach my $line (@lines) {
5797: my ($name,$descrip)=split(/:/,$line);
5798: if ($name ne $which ) { next; }
5799: chomp($line);
5800: my @config=split(/:/,$line);
5801: $config{'name'}=$config[0];
5802: $config{'description'}=$config[1];
5803: $config{'CODElocation'}=$config[2];
5804: $config{'CODEstart'}=$config[3];
5805: $config{'CODElength'}=$config[4];
5806: $config{'IDstart'}=$config[5];
5807: $config{'IDlength'}=$config[6];
5808: $config{'Qstart'}=$config[7];
5809: $config{'Qlength'}=$config[8];
5810: $config{'Qoff'}=$config[9];
5811: $config{'Qon'}=$config[10];
5812: $config{'PaperID'}=$config[11];
5813: $config{'PaperIDlength'}=$config[12];
5814: $config{'FirstName'}=$config[13];
5815: $config{'FirstNamelength'}=$config[14];
5816: $config{'LastName'}=$config[15];
5817: $config{'LastNamelength'}=$config[16];
5818: $config{'BubblesPerRow'}=$config[17];
5819: last;
5820: }
5821: return %config;
5822: }
5823:
5824: =pod
5825:
5826: =item username_to_idmap
5827:
5828: creates a hash keyed by student/employee ID with values of the corresponding
5829: student username:domain.
5830:
5831: Arguments:
5832:
5833: $classlist - reference to the class list hash. This is a hash
5834: keyed by student name:domain whose elements are references
5835: to arrays containing various chunks of information
5836: about the student. (See loncoursedata for more info).
5837:
5838: Returns
5839: %idmap - the constructed hash
5840:
5841: =cut
5842:
5843: sub username_to_idmap {
5844: my ($classlist)= @_;
5845: my %idmap;
5846: foreach my $student (keys(%$classlist)) {
5847: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5848: $student;
5849: }
5850: return %idmap;
5851: }
5852:
5853: =pod
5854:
5855: =item scantron_fixup_scanline
5856:
5857: Process a requested correction to a scanline.
5858:
5859: Arguments:
5860: $scantron_config - hash from &get_scantron_config()
5861: $scan_data - hash of correction information
5862: (see &scantron_getfile())
5863: $line - existing scanline
5864: $whichline - line number of the passed in scanline
5865: $field - type of change to process
5866: (either
5867: 'ID' -> correct the student/employee ID
5868: 'CODE' -> correct the CODE
5869: 'answer' -> fixup the submitted answers)
5870:
5871: $args - hash of additional info,
5872: - 'ID'
5873: 'newid' -> studentID to use in replacement
5874: of existing one
5875: - 'CODE'
5876: 'CODE_ignore_dup' - set to true if duplicates
5877: should be ignored.
5878: 'CODE' - is new code or 'use_unfound'
5879: if the existing unfound code should
5880: be used as is
5881: - 'answer'
5882: 'response' - new answer or 'none' if blank
5883: 'question' - the bubble line to change
5884: 'questionnum' - the question identifier,
5885: may include subquestion.
5886:
5887: Returns:
5888: $line - the modified scanline
5889:
5890: Side effects:
5891: $scan_data - may be updated
5892:
5893: =cut
5894:
5895:
5896: sub scantron_fixup_scanline {
5897: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5898: if ($field eq 'ID') {
5899: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5900: return ($line,1,'New value too large');
5901: }
5902: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5903: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5904: $args->{'newid'});
5905: }
5906: substr($line,$$scantron_config{'IDstart'}-1,
5907: $$scantron_config{'IDlength'})=$args->{'newid'};
5908: if ($args->{'newid'}=~/^\s*$/) {
5909: &scan_data($scan_data,"$whichline.user",
5910: $args->{'username'}.':'.$args->{'domain'});
5911: }
5912: } elsif ($field eq 'CODE') {
5913: if ($args->{'CODE_ignore_dup'}) {
5914: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5915: }
5916: &scan_data($scan_data,"$whichline.useCODE",'1');
5917: if ($args->{'CODE'} ne 'use_unfound') {
5918: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5919: return ($line,1,'New CODE value too large');
5920: }
5921: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5922: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5923: }
5924: substr($line,$$scantron_config{'CODEstart'}-1,
5925: $$scantron_config{'CODElength'})=$args->{'CODE'};
5926: }
5927: } elsif ($field eq 'answer') {
5928: my $length=$scantron_config->{'Qlength'};
5929: my $off=$scantron_config->{'Qoff'};
5930: my $on=$scantron_config->{'Qon'};
5931: my $answer=${off}x$length;
5932: if ($args->{'response'} eq 'none') {
5933: &scan_data($scan_data,
5934: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5935: } else {
5936: if ($on eq 'letter') {
5937: my @alphabet=('A'..'Z');
5938: $answer=$alphabet[$args->{'response'}];
5939: } elsif ($on eq 'number') {
5940: $answer=$args->{'response'}+1;
5941: if ($answer == 10) { $answer = '0'; }
5942: } else {
5943: substr($answer,$args->{'response'},1)=$on;
5944: }
5945: &scan_data($scan_data,
5946: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5947: }
5948: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5949: substr($line,$where-1,$length)=$answer;
5950: }
5951: return $line;
5952: }
5953:
5954: =pod
5955:
5956: =item scan_data
5957:
5958: Edit or look up an item in the scan_data hash.
5959:
5960: Arguments:
5961: $scan_data - The hash (see scantron_getfile)
5962: $key - shorthand of the key to edit (actual key is
5963: scantronfilename_key).
5964: $data - New value of the hash entry.
5965: $delete - If true, the entry is removed from the hash.
5966:
5967: Returns:
5968: The new value of the hash table field (undefined if deleted).
5969:
5970: =cut
5971:
5972:
5973: sub scan_data {
5974: my ($scan_data,$key,$value,$delete)=@_;
5975: my $filename=$env{'form.scantron_selectfile'};
5976: if (defined($value)) {
5977: $scan_data->{$filename.'_'.$key} = $value;
5978: }
5979: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5980: return $scan_data->{$filename.'_'.$key};
5981: }
5982:
5983: # ----- These first few routines are general use routines.----
5984:
5985: # Return the number of occurences of a pattern in a string.
5986:
5987: sub occurence_count {
5988: my ($string, $pattern) = @_;
5989:
5990: my @matches = ($string =~ /$pattern/g);
5991:
5992: return scalar(@matches);
5993: }
5994:
5995:
5996: # Take a string known to have digits and convert all the
5997: # digits into letters in the range J,A..I.
5998:
5999: sub digits_to_letters {
6000: my ($input) = @_;
6001:
6002: my @alphabet = ('J', 'A'..'I');
6003:
6004: my @input = split(//, $input);
6005: my $output ='';
6006: for (my $i = 0; $i < scalar(@input); $i++) {
6007: if ($input[$i] =~ /\d/) {
6008: $output .= $alphabet[$input[$i]];
6009: } else {
6010: $output .= $input[$i];
6011: }
6012: }
6013: return $output;
6014: }
6015:
6016: =pod
6017:
6018: =item scantron_parse_scanline
6019:
6020: Decodes a scanline from the selected scantron file
6021:
6022: Arguments:
6023: line - The text of the scantron file line to process
6024: whichline - Line number
6025: scantron_config - Hash describing the format of the scantron lines.
6026: scan_data - Hash of extra information about the scanline
6027: (see scantron_getfile for more information)
6028: just_header - True if should not process question answers but only
6029: the stuff to the left of the answers.
6030: randomorder - True if randomorder in use
6031: randompick - True if randompick in use
6032: sequence - Exam folder URL
6033: master_seq - Ref to array containing symbs in exam folder
6034: symb_to_resource - Ref to hash of symbs for resources in exam folder
6035: (corresponding values are resource objects)
6036: partids_by_symb - Ref to hash of symb -> array ref of partIDs
6037: orderedforcode - Ref to hash of arrays. keys are CODEs and values
6038: are refs to an array of resource objects, ordered
6039: according to order used for CODE, when randomorder
6040: and or randompick are in use.
6041: respnumlookup - Ref to hash mapping question numbers in bubble lines
6042: for current line to question number used for same question
6043: in "Master Sequence" (as seen by Course Coordinator).
6044: startline - Ref to hash where key is question number (0 is first)
6045: and value is number of first bubble line for current
6046: student or code-based randompick and/or randomorder.
6047: totalref - Ref of scalar used to score total number of bubble
6048: lines needed for responses in a scan line (used when
6049: randompick in use.
6050:
6051: Returns:
6052: Hash containing the result of parsing the scanline
6053:
6054: Keys are all proceeded by the string 'scantron.'
6055:
6056: CODE - the CODE in use for this scanline
6057: useCODE - 1 if the CODE is invalid but it usage has been forced
6058: by the operator
6059: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
6060: CODEs were selected, but the usage has been
6061: forced by the operator
6062: ID - student/employee ID
6063: PaperID - if used, the ID number printed on the sheet when the
6064: paper was scanned
6065: FirstName - first name from the sheet
6066: LastName - last name from the sheet
6067:
6068: if just_header was not true these key may also exist
6069:
6070: missingerror - a list of bubble ranges that are considered to be answers
6071: to a single question that don't have any bubbles filled in.
6072: Of the form questionnumber:firstbubblenumber:count.
6073: doubleerror - a list of bubble ranges that are considered to be answers
6074: to a single question that have more than one bubble filled in.
6075: Of the form questionnumber::firstbubblenumber:count
6076:
6077: In the above, count is the number of bubble responses in the
6078: input line needed to represent the possible answers to the question.
6079: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
6080: per line would have count = 2.
6081:
6082: maxquest - the number of the last bubble line that was parsed
6083:
6084: (<number> starts at 1)
6085: <number>.answer - zero or more letters representing the selected
6086: letters from the scanline for the bubble line
6087: <number>.
6088: if blank there was either no bubble or there where
6089: multiple bubbles, (consult the keys missingerror and
6090: doubleerror if this is an error condition)
6091:
6092: =cut
6093:
6094: sub scantron_parse_scanline {
6095: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6096: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6097: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6098:
6099: my %record;
6100: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6101: if (!($$scantron_config{'CODElocation'} eq 0 ||
6102: $$scantron_config{'CODElocation'} eq 'none')) {
6103: if ($$scantron_config{'CODElocation'} < 0 ||
6104: $$scantron_config{'CODElocation'} eq 'letter' ||
6105: $$scantron_config{'CODElocation'} eq 'number') {
6106: $record{'scantron.CODE'}=substr($data,
6107: $$scantron_config{'CODEstart'}-1,
6108: $$scantron_config{'CODElength'});
6109: if (&scan_data($scan_data,"$whichline.useCODE")) {
6110: $record{'scantron.useCODE'}=1;
6111: }
6112: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6113: $record{'scantron.CODE_ignore_dup'}=1;
6114: }
6115: } else {
6116: #FIXME interpret first N questions
6117: }
6118: }
6119: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6120: $$scantron_config{'IDlength'});
6121: $record{'scantron.PaperID'}=
6122: substr($data,$$scantron_config{'PaperID'}-1,
6123: $$scantron_config{'PaperIDlength'});
6124: $record{'scantron.FirstName'}=
6125: substr($data,$$scantron_config{'FirstName'}-1,
6126: $$scantron_config{'FirstNamelength'});
6127: $record{'scantron.LastName'}=
6128: substr($data,$$scantron_config{'LastName'}-1,
6129: $$scantron_config{'LastNamelength'});
6130: if ($just_header) { return \%record; }
6131:
6132: my @alphabet=('A'..'Z');
6133: my $questnum=0;
6134: my $ansnum =1; # Multiple 'answer lines'/question.
6135:
6136: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6137: if ($randompick || $randomorder) {
6138: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6139: $master_seq,$symb_to_resource,
6140: $partids_by_symb,$orderedforcode,
6141: $respnumlookup,$startline);
6142: if ($total) {
6143: $lastpos = $total*$$scantron_config{'Qlength'};
6144: }
6145: if (ref($totalref)) {
6146: $$totalref = $total;
6147: }
6148: }
6149: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6150: chomp($questions); # Get rid of any trailing \n.
6151: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6152: while (length($questions)) {
6153: my $answers_needed;
6154: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6155: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6156: } else {
6157: $answers_needed = $bubble_lines_per_response{$questnum};
6158: }
6159: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6160: || 1;
6161: $questnum++;
6162: my $quest_id = $questnum;
6163: my $currentquest = substr($questions,0,$answer_length);
6164: $questions = substr($questions,$answer_length);
6165: if (length($currentquest) < $answer_length) { next; }
6166:
6167: my $subdivided;
6168: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6169: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6170: } else {
6171: $subdivided = $subdivided_bubble_lines{$questnum-1};
6172: }
6173: if ($subdivided =~ /,/) {
6174: my $subquestnum = 1;
6175: my $subquestions = $currentquest;
6176: my @subanswers_needed = split(/,/,$subdivided);
6177: foreach my $subans (@subanswers_needed) {
6178: my $subans_length =
6179: ($$scantron_config{'Qlength'} * $subans) || 1;
6180: my $currsubquest = substr($subquestions,0,$subans_length);
6181: $subquestions = substr($subquestions,$subans_length);
6182: $quest_id = "$questnum.$subquestnum";
6183: if (($$scantron_config{'Qon'} eq 'letter') ||
6184: ($$scantron_config{'Qon'} eq 'number')) {
6185: $ansnum = &scantron_validator_lettnum($ansnum,
6186: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6187: \@alphabet,\%record,$scantron_config,$scan_data,
6188: $randomorder,$randompick,$respnumlookup);
6189: } else {
6190: $ansnum = &scantron_validator_positional($ansnum,
6191: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6192: \@alphabet,\%record,$scantron_config,$scan_data,
6193: $randomorder,$randompick,$respnumlookup);
6194: }
6195: $subquestnum ++;
6196: }
6197: } else {
6198: if (($$scantron_config{'Qon'} eq 'letter') ||
6199: ($$scantron_config{'Qon'} eq 'number')) {
6200: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6201: $quest_id,$answers_needed,$currentquest,$whichline,
6202: \@alphabet,\%record,$scantron_config,$scan_data,
6203: $randomorder,$randompick,$respnumlookup);
6204: } else {
6205: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6206: $quest_id,$answers_needed,$currentquest,$whichline,
6207: \@alphabet,\%record,$scantron_config,$scan_data,
6208: $randomorder,$randompick,$respnumlookup);
6209: }
6210: }
6211: }
6212: $record{'scantron.maxquest'}=$questnum;
6213: return \%record;
6214: }
6215:
6216: sub get_master_seq {
6217: my ($resources,$master_seq,$symb_to_resource) = @_;
6218: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6219: (ref($symb_to_resource) eq 'HASH'));
6220: my $resource_error;
6221: foreach my $resource (@{$resources}) {
6222: my $ressymb;
6223: if (ref($resource)) {
6224: $ressymb = $resource->symb();
6225: push(@{$master_seq},$ressymb);
6226: $symb_to_resource->{$ressymb} = $resource;
6227: } else {
6228: $resource_error = 1;
6229: last;
6230: }
6231: }
6232: return $resource_error;
6233: }
6234:
6235: sub get_respnum_lookups {
6236: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6237: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6238: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6239: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6240: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6241: (ref($startline) eq 'HASH'));
6242: my ($user,$scancode);
6243: if ((exists($record->{'scantron.CODE'})) &&
6244: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6245: $scancode = $record->{'scantron.CODE'};
6246: } else {
6247: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6248: }
6249: my @mapresources =
6250: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6251: $orderedforcode);
6252: my $total = 0;
6253: my $count = 0;
6254: foreach my $resource (@mapresources) {
6255: my $id = $resource->id();
6256: my $symb = $resource->symb();
6257: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6258: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6259: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6260: if ($respnum ne '') {
6261: $respnumlookup->{$count} = $respnum;
6262: $startline->{$count} = $total;
6263: $total += $bubble_lines_per_response{$respnum};
6264: $count ++;
6265: }
6266: }
6267: }
6268: }
6269: return $total;
6270: }
6271:
6272: sub scantron_validator_lettnum {
6273: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6274: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6275: $randompick,$respnumlookup) = @_;
6276:
6277: # Qon 'letter' implies for each slot in currquest we have:
6278: # ? or * for doubles, a letter in A-Z for a bubble, and
6279: # about anything else (esp. a value of Qoff) for missing
6280: # bubbles.
6281: #
6282: # Qon 'number' implies each slot gives a digit that indexes the
6283: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6284: # and * or ? for double bubbles on a single line.
6285: #
6286:
6287: my $matchon;
6288: if ($$scantron_config{'Qon'} eq 'letter') {
6289: $matchon = '[A-Z]';
6290: } elsif ($$scantron_config{'Qon'} eq 'number') {
6291: $matchon = '\d';
6292: }
6293: my $occurrences = 0;
6294: my $responsenum = $questnum-1;
6295: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6296: $responsenum = $respnumlookup->{$questnum-1}
6297: }
6298: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6299: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6300: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6301: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6302: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6303: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6304: my @singlelines = split('',$currquest);
6305: foreach my $entry (@singlelines) {
6306: $occurrences = &occurence_count($entry,$matchon);
6307: if ($occurrences > 1) {
6308: last;
6309: }
6310: }
6311: } else {
6312: $occurrences = &occurence_count($currquest,$matchon);
6313: }
6314: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6315: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6316: for (my $ans=0; $ans<$answers_needed; $ans++) {
6317: my $bubble = substr($currquest,$ans,1);
6318: if ($bubble =~ /$matchon/ ) {
6319: if ($$scantron_config{'Qon'} eq 'number') {
6320: if ($bubble == 0) {
6321: $bubble = 10;
6322: }
6323: $record->{"scantron.$ansnum.answer"} =
6324: $alphabet->[$bubble-1];
6325: } else {
6326: $record->{"scantron.$ansnum.answer"} = $bubble;
6327: }
6328: } else {
6329: $record->{"scantron.$ansnum.answer"}='';
6330: }
6331: $ansnum++;
6332: }
6333: } elsif (!defined($currquest)
6334: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6335: || (&occurence_count($currquest,$matchon) == 0)) {
6336: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6337: $record->{"scantron.$ansnum.answer"}='';
6338: $ansnum++;
6339: }
6340: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6341: push(@{$record->{'scantron.missingerror'}},$quest_id);
6342: }
6343: } else {
6344: if ($$scantron_config{'Qon'} eq 'number') {
6345: $currquest = &digits_to_letters($currquest);
6346: }
6347: for (my $ans=0; $ans<$answers_needed; $ans++) {
6348: my $bubble = substr($currquest,$ans,1);
6349: $record->{"scantron.$ansnum.answer"} = $bubble;
6350: $ansnum++;
6351: }
6352: }
6353: return $ansnum;
6354: }
6355:
6356: sub scantron_validator_positional {
6357: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6358: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6359: $randomorder,$randompick,$respnumlookup) = @_;
6360:
6361: # Otherwise there's a positional notation;
6362: # each bubble line requires Qlength items, and there are filled in
6363: # bubbles for each case where there 'Qon' characters.
6364: #
6365:
6366: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6367:
6368: # If the split only gives us one element.. the full length of the
6369: # answer string, no bubbles are filled in:
6370:
6371: if ($answers_needed eq '') {
6372: return;
6373: }
6374:
6375: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6376: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6377: $record->{"scantron.$ansnum.answer"}='';
6378: $ansnum++;
6379: }
6380: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6381: push(@{$record->{"scantron.missingerror"}},$quest_id);
6382: }
6383: } elsif (scalar(@array) == 2) {
6384: my $location = length($array[0]);
6385: my $line_num = int($location / $$scantron_config{'Qlength'});
6386: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6387: for (my $ans=0; $ans<$answers_needed; $ans++) {
6388: if ($ans eq $line_num) {
6389: $record->{"scantron.$ansnum.answer"} = $bubble;
6390: } else {
6391: $record->{"scantron.$ansnum.answer"} = ' ';
6392: }
6393: $ansnum++;
6394: }
6395: } else {
6396: # If there's more than one instance of a bubble character
6397: # That's a double bubble; with positional notation we can
6398: # record all the bubbles filled in as well as the
6399: # fact this response consists of multiple bubbles.
6400: #
6401: my $responsenum = $questnum-1;
6402: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6403: $responsenum = $respnumlookup->{$questnum-1}
6404: }
6405: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6406: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6407: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6408: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6409: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6410: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6411: my $doubleerror = 0;
6412: while (($currquest >= $$scantron_config{'Qlength'}) &&
6413: (!$doubleerror)) {
6414: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6415: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6416: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6417: if (length(@currarray) > 2) {
6418: $doubleerror = 1;
6419: }
6420: }
6421: if ($doubleerror) {
6422: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6423: }
6424: } else {
6425: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6426: }
6427: my $item = $ansnum;
6428: for (my $ans=0; $ans<$answers_needed; $ans++) {
6429: $record->{"scantron.$item.answer"} = '';
6430: $item ++;
6431: }
6432:
6433: my @ans=@array;
6434: my $i=0;
6435: my $increment = 0;
6436: while ($#ans) {
6437: $i+=length($ans[0]) + $increment;
6438: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6439: my $bubble = $i%$$scantron_config{'Qlength'};
6440: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6441: shift(@ans);
6442: $increment = 1;
6443: }
6444: $ansnum += $answers_needed;
6445: }
6446: return $ansnum;
6447: }
6448:
6449: =pod
6450:
6451: =item scantron_add_delay
6452:
6453: Adds an error message that occurred during the grading phase to a
6454: queue of messages to be shown after grading pass is complete
6455:
6456: Arguments:
6457: $delayqueue - arrary ref of hash ref of error messages
6458: $scanline - the scanline that caused the error
6459: $errormesage - the error message
6460: $errorcode - a numeric code for the error
6461:
6462: Side Effects:
6463: updates the $delayqueue to have a new hash ref of the error
6464:
6465: =cut
6466:
6467: sub scantron_add_delay {
6468: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6469: push(@$delayqueue,
6470: {'line' => $scanline, 'emsg' => $errormessage,
6471: 'ecode' => $errorcode }
6472: );
6473: }
6474:
6475: =pod
6476:
6477: =item scantron_find_student
6478:
6479: Finds the username for the current scanline
6480:
6481: Arguments:
6482: $scantron_record - hash result from scantron_parse_scanline
6483: $scan_data - hash of correction information
6484: (see &scantron_getfile() form more information)
6485: $idmap - hash from &username_to_idmap()
6486: $line - number of current scanline
6487:
6488: Returns:
6489: Either 'username:domain' or undef if unknown
6490:
6491: =cut
6492:
6493: sub scantron_find_student {
6494: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6495: my $scanID=$$scantron_record{'scantron.ID'};
6496: if ($scanID =~ /^\s*$/) {
6497: return &scan_data($scan_data,"$line.user");
6498: }
6499: foreach my $id (keys(%$idmap)) {
6500: if (lc($id) eq lc($scanID)) {
6501: return $$idmap{$id};
6502: }
6503: }
6504: return undef;
6505: }
6506:
6507: =pod
6508:
6509: =item scantron_filter
6510:
6511: Filter sub for lonnavmaps, filters out hidden resources if ignore
6512: hidden resources was selected
6513:
6514: =cut
6515:
6516: sub scantron_filter {
6517: my ($curres)=@_;
6518:
6519: if (ref($curres) && $curres->is_problem()) {
6520: # if the user has asked to not have either hidden
6521: # or 'randomout' controlled resources to be graded
6522: # don't include them
6523: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6524: && $curres->randomout) {
6525: return 0;
6526: }
6527: return 1;
6528: }
6529: return 0;
6530: }
6531:
6532: =pod
6533:
6534: =item scantron_process_corrections
6535:
6536: Gets correction information out of submitted form data and corrects
6537: the scanline
6538:
6539: =cut
6540:
6541: sub scantron_process_corrections {
6542: my ($r) = @_;
6543: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6544: my ($scanlines,$scan_data)=&scantron_getfile();
6545: my $classlist=&Apache::loncoursedata::get_classlist();
6546: my $which=$env{'form.scantron_line'};
6547: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6548: my ($skip,$err,$errmsg);
6549: if ($env{'form.scantron_skip_record'}) {
6550: $skip=1;
6551: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6552: my $newstudent=$env{'form.scantron_username'}.':'.
6553: $env{'form.scantron_domain'};
6554: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6555: ($line,$err,$errmsg)=
6556: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6557: 'ID',{'newid'=>$newid,
6558: 'username'=>$env{'form.scantron_username'},
6559: 'domain'=>$env{'form.scantron_domain'}});
6560: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6561: my $resolution=$env{'form.scantron_CODE_resolution'};
6562: my $newCODE;
6563: my %args;
6564: if ($resolution eq 'use_unfound') {
6565: $newCODE='use_unfound';
6566: } elsif ($resolution eq 'use_found') {
6567: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6568: } elsif ($resolution eq 'use_typed') {
6569: $newCODE=$env{'form.scantron_CODE_newvalue'};
6570: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6571: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6572: }
6573: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6574: $args{'CODE_ignore_dup'}=1;
6575: }
6576: $args{'CODE'}=$newCODE;
6577: ($line,$err,$errmsg)=
6578: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6579: 'CODE',\%args);
6580: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6581: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6582: ($line,$err,$errmsg)=
6583: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6584: $which,'answer',
6585: { 'question'=>$question,
6586: 'response'=>$env{"form.scantron_correct_Q_$question"},
6587: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6588: if ($err) { last; }
6589: }
6590: }
6591: if ($err) {
6592: $r->print(
6593: '<p class="LC_error">'
6594: .&mt('Unable to accept last correction, an error occurred: [_1]',
6595: $errmsg)
6596: .'</p>');
6597: } else {
6598: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6599: &scantron_putfile($scanlines,$scan_data);
6600: }
6601: }
6602:
6603: =pod
6604:
6605: =item reset_skipping_status
6606:
6607: Forgets the current set of remember skipped scanlines (and thus
6608: reverts back to considering all lines in the
6609: scantron_skipped_<filename> file)
6610:
6611: =cut
6612:
6613: sub reset_skipping_status {
6614: my ($scanlines,$scan_data)=&scantron_getfile();
6615: &scan_data($scan_data,'remember_skipping',undef,1);
6616: &scantron_putfile(undef,$scan_data);
6617: }
6618:
6619: =pod
6620:
6621: =item start_skipping
6622:
6623: Marks a scanline to be skipped.
6624:
6625: =cut
6626:
6627: sub start_skipping {
6628: my ($scan_data,$i)=@_;
6629: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6630: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6631: $remembered{$i}=2;
6632: } else {
6633: $remembered{$i}=1;
6634: }
6635: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6636: }
6637:
6638: =pod
6639:
6640: =item should_be_skipped
6641:
6642: Checks whether a scanline should be skipped.
6643:
6644: =cut
6645:
6646: sub should_be_skipped {
6647: my ($scanlines,$scan_data,$i)=@_;
6648: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6649: # not redoing old skips
6650: if ($scanlines->{'skipped'}[$i]) { return 1; }
6651: return 0;
6652: }
6653: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6654:
6655: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6656: return 0;
6657: }
6658: return 1;
6659: }
6660:
6661: =pod
6662:
6663: =item remember_current_skipped
6664:
6665: Discovers what scanlines are in the scantron_skipped_<filename>
6666: file and remembers them into scan_data for later use.
6667:
6668: =cut
6669:
6670: sub remember_current_skipped {
6671: my ($scanlines,$scan_data)=&scantron_getfile();
6672: my %to_remember;
6673: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6674: if ($scanlines->{'skipped'}[$i]) {
6675: $to_remember{$i}=1;
6676: }
6677: }
6678:
6679: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6680: &scantron_putfile(undef,$scan_data);
6681: }
6682:
6683: =pod
6684:
6685: =item check_for_error
6686:
6687: Checks if there was an error when attempting to remove a specific
6688: scantron_.. bubblesheet data file. Prints out an error if
6689: something went wrong.
6690:
6691: =cut
6692:
6693: sub check_for_error {
6694: my ($r,$result)=@_;
6695: if ($result ne 'ok' && $result ne 'not_found' ) {
6696: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6697: }
6698: }
6699:
6700: =pod
6701:
6702: =item scantron_warning_screen
6703:
6704: Interstitial screen to make sure the operator has selected the
6705: correct options before we start the validation phase.
6706:
6707: =cut
6708:
6709: sub scantron_warning_screen {
6710: my ($button_text)=@_;
6711: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6712: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6713: my $CODElist;
6714: if ($scantron_config{'CODElocation'} &&
6715: $scantron_config{'CODEstart'} &&
6716: $scantron_config{'CODElength'}) {
6717: $CODElist=$env{'form.scantron_CODElist'};
6718: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6719: $CODElist=
6720: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6721: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6722: }
6723: my $lastbubblepoints;
6724: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6725: $lastbubblepoints =
6726: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6727: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6728: }
6729: return ('
6730: <p>
6731: <span class="LC_warning">
6732: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6733: </p>
6734: <table>
6735: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6736: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6737: '.$CODElist.$lastbubblepoints.'
6738: </table>
6739: <br />
6740: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
6741: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
6742:
6743: <br />
6744: ');
6745: }
6746:
6747: =pod
6748:
6749: =item scantron_do_warning
6750:
6751: Check if the operator has picked something for all required
6752: fields. Error out if something is missing.
6753:
6754: =cut
6755:
6756: sub scantron_do_warning {
6757: my ($r)=@_;
6758: my ($symb)=&get_symb($r);
6759: if (!$symb) {return '';}
6760: my $default_form_data=&defaultFormData($symb);
6761: $r->print(&scantron_form_start().$default_form_data);
6762: if ( $env{'form.selectpage'} eq '' ||
6763: $env{'form.scantron_selectfile'} eq '' ||
6764: $env{'form.scantron_format'} eq '' ) {
6765: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6766: if ( $env{'form.selectpage'} eq '') {
6767: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6768: }
6769: if ( $env{'form.scantron_selectfile'} eq '') {
6770: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6771: }
6772: if ( $env{'form.scantron_format'} eq '') {
6773: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6774: }
6775: } else {
6776: my $warning=&scantron_warning_screen('Grading: Validate Records');
6777: my $bubbledbyhand=&hand_bubble_option();
6778: $r->print('
6779: '.$warning.$bubbledbyhand.'
6780: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6781: <input type="hidden" name="command" value="scantron_validate" />
6782: ');
6783: }
6784: $r->print("</form><br />".&show_grading_menu_form($symb));
6785: return '';
6786: }
6787:
6788: =pod
6789:
6790: =item scantron_form_start
6791:
6792: html hidden input for remembering all selected grading options
6793:
6794: =cut
6795:
6796: sub scantron_form_start {
6797: my ($max_bubble)=@_;
6798: my $result= <<SCANTRONFORM;
6799: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6800: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6801: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6802: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6803: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6804: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6805: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6806: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6807: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6808: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6809: SCANTRONFORM
6810:
6811: my $line = 0;
6812: while (defined($env{"form.scantron.bubblelines.$line"})) {
6813: my $chunk =
6814: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6815: $chunk .=
6816: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6817: $chunk .=
6818: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6819: $chunk .=
6820: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6821: $chunk .=
6822: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
6823: $result .= $chunk;
6824: $line++;
6825: }
6826: return $result;
6827: }
6828:
6829: =pod
6830:
6831: =item scantron_validate_file
6832:
6833: Dispatch routine for doing validation of a bubblesheet data file.
6834:
6835: Also processes any necessary information resets that need to
6836: occur before validation begins (ignore previous corrections,
6837: restarting the skipped records processing)
6838:
6839: =cut
6840:
6841: sub scantron_validate_file {
6842: my ($r) = @_;
6843: my ($symb)=&get_symb($r);
6844: if (!$symb) {return '';}
6845: my $default_form_data=&defaultFormData($symb);
6846:
6847: # do the detection of only doing skipped records first before we delete
6848: # them when doing the corrections reset
6849: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6850: &reset_skipping_status();
6851: }
6852: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6853: &remember_current_skipped();
6854: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6855: }
6856:
6857: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6858: &check_for_error($r,&scantron_remove_file('corrected'));
6859: &check_for_error($r,&scantron_remove_file('skipped'));
6860: &check_for_error($r,&scantron_remove_scan_data());
6861: $env{'form.scantron_options_ignore'}='done';
6862: }
6863:
6864: if ($env{'form.scantron_corrections'}) {
6865: &scantron_process_corrections($r);
6866: }
6867: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6868: #get the student pick code ready
6869: $r->print(&Apache::loncommon::studentbrowser_javascript());
6870: my $nav_error;
6871: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6872: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6873: if ($nav_error) {
6874: $r->print(&navmap_errormsg());
6875: return '';
6876: }
6877: my $result=&scantron_form_start($max_bubble).$default_form_data;
6878: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6879: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6880: }
6881: $r->print($result);
6882:
6883: my @validate_phases=( 'sequence',
6884: 'ID',
6885: 'CODE',
6886: 'doublebubble',
6887: 'missingbubbles');
6888: if (!$env{'form.validatepass'}) {
6889: $env{'form.validatepass'} = 0;
6890: }
6891: my $currentphase=$env{'form.validatepass'};
6892:
6893:
6894: my $stop=0;
6895: while (!$stop && $currentphase < scalar(@validate_phases)) {
6896: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6897: $r->rflush();
6898:
6899: my $which="scantron_validate_".$validate_phases[$currentphase];
6900: {
6901: no strict 'refs';
6902: ($stop,$currentphase)=&$which($r,$currentphase);
6903: }
6904: }
6905: if (!$stop) {
6906: my $warning=&scantron_warning_screen('Start Grading');
6907: $r->print(&mt('Validation process complete.').'<br />'.
6908: $warning.
6909: &mt('Perform verification for each student after storage of submissions?').
6910: ' <span class="LC_nobreak"><label>'.
6911: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6912: (' 'x3).'<label>'.
6913: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6914: '</label></span><br />'.
6915: &mt('Grading will take longer if you use verification.').'<br />'.
6916: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
6917: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6918: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6919: } else {
6920: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6921: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6922: }
6923: if ($stop) {
6924: if ($validate_phases[$currentphase] eq 'sequence') {
6925: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6926: $r->print(' '.&mt('this error').' <br />');
6927:
6928: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
6929: } else {
6930: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6931: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6932: } else {
6933: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6934: }
6935: $r->print(' '.&mt('using corrected info').' <br />');
6936: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6937: $r->print(" ".&mt("this scanline saving it for later."));
6938: }
6939: }
6940: $r->print(" </form><br />".&show_grading_menu_form($symb));
6941: return '';
6942: }
6943:
6944:
6945: =pod
6946:
6947: =item scantron_remove_file
6948:
6949: Removes the requested bubblesheet data file, makes sure that
6950: scantron_original_<filename> is never removed
6951:
6952:
6953: =cut
6954:
6955: sub scantron_remove_file {
6956: my ($which)=@_;
6957: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6958: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6959: my $file='scantron_';
6960: if ($which eq 'corrected' || $which eq 'skipped') {
6961: $file.=$which.'_';
6962: } else {
6963: return 'refused';
6964: }
6965: $file.=$env{'form.scantron_selectfile'};
6966: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6967: }
6968:
6969:
6970: =pod
6971:
6972: =item scantron_remove_scan_data
6973:
6974: Removes all scan_data correction for the requested bubblesheet
6975: data file. (In the case that both the are doing skipped records we need
6976: to remember the old skipped lines for the time being so that element
6977: persists for a while.)
6978:
6979: =cut
6980:
6981: sub scantron_remove_scan_data {
6982: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6983: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6984: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6985: my @todelete;
6986: my $filename=$env{'form.scantron_selectfile'};
6987: foreach my $key (@keys) {
6988: if ($key=~/^\Q$filename\E_/) {
6989: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6990: $key=~/remember_skipping/) {
6991: next;
6992: }
6993: push(@todelete,$key);
6994: }
6995: }
6996: my $result;
6997: if (@todelete) {
6998: $result = &Apache::lonnet::del('nohist_scantrondata',
6999: \@todelete,$cdom,$cname);
7000: } else {
7001: $result = 'ok';
7002: }
7003: return $result;
7004: }
7005:
7006:
7007: =pod
7008:
7009: =item scantron_getfile
7010:
7011: Fetches the requested bubblesheet data file (all 3 versions), and
7012: the scan_data hash
7013:
7014: Arguments:
7015: None
7016:
7017: Returns:
7018: 2 hash references
7019:
7020: - first one has
7021: orig -
7022: corrected -
7023: skipped - each of which points to an array ref of the specified
7024: file broken up into individual lines
7025: count - number of scanlines
7026:
7027: - second is the scan_data hash possible keys are
7028: ($number refers to scanline numbered $number and thus the key affects
7029: only that scanline
7030: $bubline refers to the specific bubble line element and the aspects
7031: refers to that specific bubble line element)
7032:
7033: $number.user - username:domain to use
7034: $number.CODE_ignore_dup
7035: - ignore the duplicate CODE error
7036: $number.useCODE
7037: - use the CODE in the scanline as is
7038: $number.no_bubble.$bubline
7039: - it is valid that there is no bubbled in bubble
7040: at $number $bubline
7041: remember_skipping
7042: - a frozen hash containing keys of $number and values
7043: of either
7044: 1 - we are on a 'do skipped records pass' and plan
7045: on processing this line
7046: 2 - we are on a 'do skipped records pass' and this
7047: scanline has been marked to skip yet again
7048:
7049: =cut
7050:
7051: sub scantron_getfile {
7052: #FIXME really would prefer a scantron directory
7053: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7054: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7055: my $lines;
7056: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7057: 'scantron_orig_'.$env{'form.scantron_selectfile'});
7058: my %scanlines;
7059: $scanlines{'orig'}=[(split("\n",$lines,-1))];
7060: my $temp=$scanlines{'orig'};
7061: $scanlines{'count'}=$#$temp;
7062:
7063: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7064: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
7065: if ($lines eq '-1') {
7066: $scanlines{'corrected'}=[];
7067: } else {
7068: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
7069: }
7070: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7071: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
7072: if ($lines eq '-1') {
7073: $scanlines{'skipped'}=[];
7074: } else {
7075: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
7076: }
7077: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
7078: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
7079: my %scan_data = @tmp;
7080: return (\%scanlines,\%scan_data);
7081: }
7082:
7083: =pod
7084:
7085: =item lonnet_putfile
7086:
7087: Wrapper routine to call &Apache::lonnet::finishuserfileupload
7088:
7089: Arguments:
7090: $contents - data to store
7091: $filename - filename to store $contents into
7092:
7093: Returns:
7094: result value from &Apache::lonnet::finishuserfileupload
7095:
7096: =cut
7097:
7098: sub lonnet_putfile {
7099: my ($contents,$filename)=@_;
7100: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7101: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7102: $env{'form.sillywaytopassafilearound'}=$contents;
7103: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7104:
7105: }
7106:
7107: =pod
7108:
7109: =item scantron_putfile
7110:
7111: Stores the current version of the bubblesheet data files, and the
7112: scan_data hash. (Does not modify the original version only the
7113: corrected and skipped versions.
7114:
7115: Arguments:
7116: $scanlines - hash ref that looks like the first return value from
7117: &scantron_getfile()
7118: $scan_data - hash ref that looks like the second return value from
7119: &scantron_getfile()
7120:
7121: =cut
7122:
7123: sub scantron_putfile {
7124: my ($scanlines,$scan_data) = @_;
7125: #FIXME really would prefer a scantron directory
7126: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7127: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7128: if ($scanlines) {
7129: my $prefix='scantron_';
7130: # no need to update orig, shouldn't change
7131: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7132: # $env{'form.scantron_selectfile'});
7133: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7134: $prefix.'corrected_'.
7135: $env{'form.scantron_selectfile'});
7136: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7137: $prefix.'skipped_'.
7138: $env{'form.scantron_selectfile'});
7139: }
7140: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7141: }
7142:
7143: =pod
7144:
7145: =item scantron_get_line
7146:
7147: Returns the correct version of the scanline
7148:
7149: Arguments:
7150: $scanlines - hash ref that looks like the first return value from
7151: &scantron_getfile()
7152: $scan_data - hash ref that looks like the second return value from
7153: &scantron_getfile()
7154: $i - number of the requested line (starts at 0)
7155:
7156: Returns:
7157: A scanline, (either the original or the corrected one if it
7158: exists), or undef if the requested scanline should be
7159: skipped. (Either because it's an skipped scanline, or it's an
7160: unskipped scanline and we are not doing a 'do skipped scanlines'
7161: pass.
7162:
7163: =cut
7164:
7165: sub scantron_get_line {
7166: my ($scanlines,$scan_data,$i)=@_;
7167: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7168: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7169: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7170: return $scanlines->{'orig'}[$i];
7171: }
7172:
7173: =pod
7174:
7175: =item scantron_todo_count
7176:
7177: Counts the number of scanlines that need processing.
7178:
7179: Arguments:
7180: $scanlines - hash ref that looks like the first return value from
7181: &scantron_getfile()
7182: $scan_data - hash ref that looks like the second return value from
7183: &scantron_getfile()
7184:
7185: Returns:
7186: $count - number of scanlines to process
7187:
7188: =cut
7189:
7190: sub get_todo_count {
7191: my ($scanlines,$scan_data)=@_;
7192: my $count=0;
7193: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7194: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7195: if ($line=~/^[\s\cz]*$/) { next; }
7196: $count++;
7197: }
7198: return $count;
7199: }
7200:
7201: =pod
7202:
7203: =item scantron_put_line
7204:
7205: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7206: data file.
7207:
7208: Arguments:
7209: $scanlines - hash ref that looks like the first return value from
7210: &scantron_getfile()
7211: $scan_data - hash ref that looks like the second return value from
7212: &scantron_getfile()
7213: $i - line number to update
7214: $newline - contents of the updated scanline
7215: $skip - if true make the line for skipping and update the
7216: 'skipped' file
7217:
7218: =cut
7219:
7220: sub scantron_put_line {
7221: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7222: if ($skip) {
7223: $scanlines->{'skipped'}[$i]=$newline;
7224: &start_skipping($scan_data,$i);
7225: return;
7226: }
7227: $scanlines->{'corrected'}[$i]=$newline;
7228: }
7229:
7230: =pod
7231:
7232: =item scantron_clear_skip
7233:
7234: Remove a line from the 'skipped' file
7235:
7236: Arguments:
7237: $scanlines - hash ref that looks like the first return value from
7238: &scantron_getfile()
7239: $scan_data - hash ref that looks like the second return value from
7240: &scantron_getfile()
7241: $i - line number to update
7242:
7243: =cut
7244:
7245: sub scantron_clear_skip {
7246: my ($scanlines,$scan_data,$i)=@_;
7247: if (exists($scanlines->{'skipped'}[$i])) {
7248: undef($scanlines->{'skipped'}[$i]);
7249: return 1;
7250: }
7251: return 0;
7252: }
7253:
7254: =pod
7255:
7256: =item scantron_filter_not_exam
7257:
7258: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7259: filter out resources that are not marked as 'exam' mode
7260:
7261: =cut
7262:
7263: sub scantron_filter_not_exam {
7264: my ($curres)=@_;
7265:
7266: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7267: # if the user has asked to not have either hidden
7268: # or 'randomout' controlled resources to be graded
7269: # don't include them
7270: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7271: && $curres->randomout) {
7272: return 0;
7273: }
7274: return 1;
7275: }
7276: return 0;
7277: }
7278:
7279: =pod
7280:
7281: =item scantron_validate_sequence
7282:
7283: Validates the selected sequence, checking for resource that are
7284: not set to exam mode.
7285:
7286: =cut
7287:
7288: sub scantron_validate_sequence {
7289: my ($r,$currentphase) = @_;
7290:
7291: my $navmap=Apache::lonnavmaps::navmap->new();
7292: unless (ref($navmap)) {
7293: $r->print(&navmap_errormsg());
7294: return (1,$currentphase);
7295: }
7296: my (undef,undef,$sequence)=
7297: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7298:
7299: my $map=$navmap->getResourceByUrl($sequence);
7300:
7301: $r->print('<input type="hidden" name="validate_sequence_exam"
7302: value="ignore" />');
7303: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7304: my @resources=
7305: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7306: if (@resources) {
7307: $r->print('<p class="LC_warning">'
7308: .&mt('Some resources in the sequence currently are not set to'
7309: .' exam mode. Grading these resources currently may not'
7310: .' work correctly.')
7311: .'</p>'
7312: );
7313: return (1,$currentphase);
7314: }
7315: }
7316:
7317: return (0,$currentphase+1);
7318: }
7319:
7320:
7321:
7322: sub scantron_validate_ID {
7323: my ($r,$currentphase) = @_;
7324:
7325: #get student info
7326: my $classlist=&Apache::loncoursedata::get_classlist();
7327: my %idmap=&username_to_idmap($classlist);
7328:
7329: #get scantron line setup
7330: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7331: my ($scanlines,$scan_data)=&scantron_getfile();
7332:
7333: my $nav_error;
7334: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7335: if ($nav_error) {
7336: $r->print(&navmap_errormsg());
7337: return(1,$currentphase);
7338: }
7339:
7340: my %found=('ids'=>{},'usernames'=>{});
7341: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7342: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7343: if ($line=~/^[\s\cz]*$/) { next; }
7344: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7345: $scan_data);
7346: my $id=$$scan_record{'scantron.ID'};
7347: my $found;
7348: foreach my $checkid (keys(%idmap)) {
7349: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7350: }
7351: if ($found) {
7352: my $username=$idmap{$found};
7353: if ($found{'ids'}{$found}) {
7354: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7355: $line,'duplicateID',$found);
7356: return(1,$currentphase);
7357: } elsif ($found{'usernames'}{$username}) {
7358: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7359: $line,'duplicateID',$username);
7360: return(1,$currentphase);
7361: }
7362: #FIXME store away line we previously saw the ID on to use above
7363: $found{'ids'}{$found}++;
7364: $found{'usernames'}{$username}++;
7365: } else {
7366: if ($id =~ /^\s*$/) {
7367: my $username=&scan_data($scan_data,"$i.user");
7368: if (defined($username) && $found{'usernames'}{$username}) {
7369: &scantron_get_correction($r,$i,$scan_record,
7370: \%scantron_config,
7371: $line,'duplicateID',$username);
7372: return(1,$currentphase);
7373: } elsif (!defined($username)) {
7374: &scantron_get_correction($r,$i,$scan_record,
7375: \%scantron_config,
7376: $line,'incorrectID');
7377: return(1,$currentphase);
7378: }
7379: $found{'usernames'}{$username}++;
7380: } else {
7381: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7382: $line,'incorrectID');
7383: return(1,$currentphase);
7384: }
7385: }
7386: }
7387:
7388: return (0,$currentphase+1);
7389: }
7390:
7391:
7392: sub scantron_get_correction {
7393: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7394: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7395: #FIXME in the case of a duplicated ID the previous line, probably need
7396: #to show both the current line and the previous one and allow skipping
7397: #the previous one or the current one
7398:
7399: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7400: $r->print(
7401: '<p class="LC_warning">'
7402: .&mt('An error was detected ([_1]) for PaperID [_2]',
7403: "<b>$error</b>",
7404: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7405: ."</p> \n");
7406: } else {
7407: $r->print(
7408: '<p class="LC_warning">'
7409: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7410: "<b>$error</b>", $i, "<pre>$line</pre>")
7411: ."</p> \n");
7412: }
7413: my $message =
7414: '<p>'
7415: .&mt('The ID on the form is [_1]',
7416: "<tt>$$scan_record{'scantron.ID'}</tt>")
7417: .'<br />'
7418: .&mt('The name on the paper is [_1], [_2]',
7419: $$scan_record{'scantron.LastName'},
7420: $$scan_record{'scantron.FirstName'})
7421: .'</p>';
7422:
7423: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7424: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7425: # Array populated for doublebubble or
7426: my @lines_to_correct; # missingbubble errors to build javascript
7427: # to validate radio button checking
7428:
7429: if ($error =~ /ID$/) {
7430: if ($error eq 'incorrectID') {
7431: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7432: "</p>\n");
7433: } elsif ($error eq 'duplicateID') {
7434: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7435: }
7436: $r->print($message);
7437: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7438: $r->print("\n<ul><li> ");
7439: #FIXME it would be nice if this sent back the user ID and
7440: #could do partial userID matches
7441: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7442: 'scantron_username','scantron_domain'));
7443: $r->print(": <input type='text' name='scantron_username' value='' />");
7444: $r->print("\n:\n".
7445: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7446:
7447: $r->print('</li>');
7448: } elsif ($error =~ /CODE$/) {
7449: if ($error eq 'incorrectCODE') {
7450: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7451: } elsif ($error eq 'duplicateCODE') {
7452: $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");
7453: }
7454: $r->print("<p>".&mt('The CODE on the form is [_1]',
7455: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7456: ."</p>\n");
7457: $r->print($message);
7458: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7459: $r->print("\n<br /> ");
7460: my $i=0;
7461: if ($error eq 'incorrectCODE'
7462: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7463: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7464: if ($closest > 0) {
7465: foreach my $testcode (@{$closest}) {
7466: my $checked='';
7467: if (!$i) { $checked=' checked="checked"'; }
7468: $r->print("
7469: <label>
7470: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7471: ".&mt("Use the similar CODE [_1] instead.",
7472: "<b><tt>".$testcode."</tt></b>")."
7473: </label>
7474: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7475: $r->print("\n<br />");
7476: $i++;
7477: }
7478: }
7479: }
7480: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7481: my $checked; if (!$i) { $checked=' checked="checked"'; }
7482: $r->print("
7483: <label>
7484: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7485: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7486: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7487: </label>");
7488: $r->print("\n<br />");
7489: }
7490:
7491: $r->print(<<ENDSCRIPT);
7492: <script type="text/javascript">
7493: function change_radio(field) {
7494: var slct=document.scantronupload.scantron_CODE_resolution;
7495: var i;
7496: for (i=0;i<slct.length;i++) {
7497: if (slct[i].value==field) { slct[i].checked=true; }
7498: }
7499: }
7500: </script>
7501: ENDSCRIPT
7502: my $href="/adm/pickcode?".
7503: "form=".&escape("scantronupload").
7504: "&scantron_format=".&escape($env{'form.scantron_format'}).
7505: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7506: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7507: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7508: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7509: $r->print("
7510: <label>
7511: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7512: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7513: "<a target='_blank' href='$href'>","</a>")."
7514: </label>
7515: ".&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\')" />'));
7516: $r->print("\n<br />");
7517: }
7518: $r->print("
7519: <label>
7520: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7521: ".&mt("Use [_1] as the CODE.",
7522: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7523: $r->print("\n<br /><br />");
7524: } elsif ($error eq 'doublebubble') {
7525: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7526:
7527: # The form field scantron_questions is acutally a list of line numbers.
7528: # represented by this form so:
7529:
7530: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7531: $respnumlookup,$startline);
7532:
7533: $r->print('<input type="hidden" name="scantron_questions" value="'.
7534: $line_list.'" />');
7535: $r->print($message);
7536: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7537: foreach my $question (@{$arg}) {
7538: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7539: $scan_record, $error,
7540: $randomorder,$randompick,
7541: $respnumlookup,$startline);
7542: push(@lines_to_correct,@linenums);
7543: }
7544: $r->print(&verify_bubbles_checked(@lines_to_correct));
7545: } elsif ($error eq 'missingbubble') {
7546: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7547: $r->print($message);
7548: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7549: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7550:
7551: # The form field scantron_questions is actually a list of line numbers not
7552: # a list of question numbers. Therefore:
7553: #
7554:
7555: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7556: $respnumlookup,$startline);
7557:
7558: $r->print('<input type="hidden" name="scantron_questions" value="'.
7559: $line_list.'" />');
7560: foreach my $question (@{$arg}) {
7561: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7562: $scan_record, $error,
7563: $randomorder,$randompick,
7564: $respnumlookup,$startline);
7565: push(@lines_to_correct,@linenums);
7566: }
7567: $r->print(&verify_bubbles_checked(@lines_to_correct));
7568: } else {
7569: $r->print("\n<ul>");
7570: }
7571: $r->print("\n</li></ul>");
7572: }
7573:
7574: sub verify_bubbles_checked {
7575: my (@ansnums) = @_;
7576: my $ansnumstr = join('","',@ansnums);
7577: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7578: my $output = (<<ENDSCRIPT);
7579: <script type="text/javascript">
7580: function verify_bubble_radio(form) {
7581: var ansnumArray = new Array ("$ansnumstr");
7582: var need_bubble_count = 0;
7583: for (var i=0; i<ansnumArray.length; i++) {
7584: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7585: var bubble_picked = 0;
7586: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7587: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7588: bubble_picked = 1;
7589: }
7590: }
7591: if (bubble_picked == 0) {
7592: need_bubble_count ++;
7593: }
7594: }
7595: }
7596: if (need_bubble_count) {
7597: alert("$warning");
7598: return;
7599: }
7600: form.submit();
7601: }
7602: </script>
7603: ENDSCRIPT
7604: return $output;
7605: }
7606:
7607: =pod
7608:
7609: =item questions_to_line_list
7610:
7611: Converts a list of questions into a string of comma separated
7612: line numbers in the answer sheet used by the questions. This is
7613: used to fill in the scantron_questions form field.
7614:
7615: Arguments:
7616: questions - Reference to an array of questions.
7617: randomorder - True if randomorder in use.
7618: randompick - True if randompick in use.
7619: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7620: for current line to question number used for same question
7621: in "Master Seqence" (as seen by Course Coordinator).
7622: startline - Reference to hash where key is question number (0 is first)
7623: and key is number of first bubble line for current student
7624: or code-based randompick and/or randomorder.
7625:
7626: =cut
7627:
7628:
7629: sub questions_to_line_list {
7630: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7631: my @lines;
7632:
7633: foreach my $item (@{$questions}) {
7634: my $question = $item;
7635: my ($first,$count,$last);
7636: if ($item =~ /^(\d+)\.(\d+)$/) {
7637: $question = $1;
7638: my $subquestion = $2;
7639: my $responsenum = $question-1;
7640: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7641: $responsenum = $respnumlookup->{$question-1};
7642: if (ref($startline) eq 'HASH') {
7643: $first = $startline->{$question-1} + 1;
7644: }
7645: } else {
7646: $first = $first_bubble_line{$responsenum} + 1;
7647: }
7648: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7649: my $subcount = 1;
7650: while ($subcount<$subquestion) {
7651: $first += $subans[$subcount-1];
7652: $subcount ++;
7653: }
7654: $count = $subans[$subquestion-1];
7655: } else {
7656: my $responsenum = $question-1;
7657: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7658: $responsenum = $respnumlookup->{$question-1};
7659: if (ref($startline) eq 'HASH') {
7660: $first = $startline->{$question-1} + 1;
7661: }
7662: } else {
7663: $first = $first_bubble_line{$responsenum} + 1;
7664: }
7665: $count = $bubble_lines_per_response{$responsenum};
7666: }
7667: $last = $first+$count-1;
7668: push(@lines, ($first..$last));
7669: }
7670: return join(',', @lines);
7671: }
7672:
7673: =pod
7674:
7675: =item prompt_for_corrections
7676:
7677: Prompts for a potentially multiline correction to the
7678: user's bubbling (factors out common code from scantron_get_correction
7679: for multi and missing bubble cases).
7680:
7681: Arguments:
7682: $r - Apache request object.
7683: $question - The question number to prompt for.
7684: $scan_config - The scantron file configuration hash.
7685: $scan_record - Reference to the hash that has the the parsed scanlines.
7686: $error - Type of error
7687: $randomorder - True if randomorder in use.
7688: $randompick - True if randompick in use.
7689: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7690: for current line to question number used for same question
7691: in "Master Seqence" (as seen by Course Coordinator).
7692: $startline - Reference to hash where key is question number (0 is first)
7693: and value is number of first bubble line for current student
7694: or code-based randompick and/or randomorder.
7695:
7696: Implicit inputs:
7697: %bubble_lines_per_response - Starting line numbers for each question.
7698: Numbered from 0 (but question numbers are from
7699: 1.
7700: %first_bubble_line - Starting bubble line for each question.
7701: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7702: type problems render as separate sub-questions,
7703: in exam mode. This hash contains a
7704: comma-separated list of the lines per
7705: sub-question.
7706: %responsetype_per_response - essayresponse, formularesponse,
7707: stringresponse, imageresponse, reactionresponse,
7708: and organicresponse type problem parts can have
7709: multiple lines per response if the weight
7710: assigned exceeds 10. In this case, only
7711: one bubble per line is permitted, but more
7712: than one line might contain bubbles, e.g.
7713: bubbling of: line 1 - J, line 2 - J,
7714: line 3 - B would assign 22 points.
7715:
7716: =cut
7717:
7718: sub prompt_for_corrections {
7719: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7720: $randompick, $respnumlookup, $startline) = @_;
7721: my ($current_line,$lines);
7722: my @linenums;
7723: my $questionnum = $question;
7724: my ($first,$responsenum);
7725: if ($question =~ /^(\d+)\.(\d+)$/) {
7726: $question = $1;
7727: my $subquestion = $2;
7728: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7729: $responsenum = $respnumlookup->{$question-1};
7730: if (ref($startline) eq 'HASH') {
7731: $first = $startline->{$question-1};
7732: }
7733: } else {
7734: $responsenum = $question-1;
7735: $first = $first_bubble_line{$responsenum} + 1;
7736: }
7737: $current_line = $first + 1 ;
7738: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7739: my $subcount = 1;
7740: while ($subcount<$subquestion) {
7741: $current_line += $subans[$subcount-1];
7742: $subcount ++;
7743: }
7744: $lines = $subans[$subquestion-1];
7745: } else {
7746: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7747: $responsenum = $respnumlookup->{$question-1};
7748: if (ref($startline) eq 'HASH') {
7749: $first = $startline->{$question-1};
7750: }
7751: } else {
7752: $responsenum = $question-1;
7753: $first = $first_bubble_line{$responsenum};
7754: }
7755: $current_line = $first + 1;
7756: $lines = $bubble_lines_per_response{$responsenum};
7757: }
7758: if ($lines > 1) {
7759: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7760: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7761: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7762: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7763: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7764: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7765: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7766: $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 />');
7767: } else {
7768: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7769: }
7770: }
7771: for (my $i =0; $i < $lines; $i++) {
7772: my $selected = $$scan_record{"scantron.$current_line.answer"};
7773: &scantron_bubble_selector($r,$scan_config,$current_line,
7774: $questionnum,$error,split('', $selected));
7775: push(@linenums,$current_line);
7776: $current_line++;
7777: }
7778: if ($lines > 1) {
7779: $r->print("<hr /><br />");
7780: }
7781: return @linenums;
7782: }
7783:
7784: =pod
7785:
7786: =item scantron_bubble_selector
7787:
7788: Generates the html radiobuttons to correct a single bubble line
7789: possibly showing the existing the selected bubbles if known
7790:
7791: Arguments:
7792: $r - Apache request object
7793: $scan_config - hash from &get_scantron_config()
7794: $line - Number of the line being displayed.
7795: $questionnum - Question number (may include subquestion)
7796: $error - Type of error.
7797: @selected - Array of bubbles picked on this line.
7798:
7799: =cut
7800:
7801: sub scantron_bubble_selector {
7802: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7803: my $max=$$scan_config{'Qlength'};
7804:
7805: my $scmode=$$scan_config{'Qon'};
7806: if ($scmode eq 'number' || $scmode eq 'letter') {
7807: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7808: ($$scan_config{'BubblesPerRow'} > 0)) {
7809: $max=$$scan_config{'BubblesPerRow'};
7810: if (($scmode eq 'number') && ($max > 10)) {
7811: $max = 10;
7812: } elsif (($scmode eq 'letter') && $max > 26) {
7813: $max = 26;
7814: }
7815: } else {
7816: $max = 10;
7817: }
7818: }
7819:
7820: my @alphabet=('A'..'Z');
7821: $r->print(&Apache::loncommon::start_data_table().
7822: &Apache::loncommon::start_data_table_row());
7823: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7824: for (my $i=0;$i<$max+1;$i++) {
7825: $r->print("\n".'<td align="center">');
7826: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7827: else { $r->print(' '); }
7828: $r->print('</td>');
7829: }
7830: $r->print(&Apache::loncommon::end_data_table_row().
7831: &Apache::loncommon::start_data_table_row());
7832: for (my $i=0;$i<$max;$i++) {
7833: $r->print("\n".
7834: '<td><label><input type="radio" name="scantron_correct_Q_'.
7835: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7836: }
7837: my $nobub_checked = ' ';
7838: if ($error eq 'missingbubble') {
7839: $nobub_checked = ' checked = "checked" ';
7840: }
7841: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7842: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7843: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7844: $line.'" value="'.$questionnum.'" /></td>');
7845: $r->print(&Apache::loncommon::end_data_table_row().
7846: &Apache::loncommon::end_data_table());
7847: }
7848:
7849: =pod
7850:
7851: =item num_matches
7852:
7853: Counts the number of characters that are the same between the two arguments.
7854:
7855: Arguments:
7856: $orig - CODE from the scanline
7857: $code - CODE to match against
7858:
7859: Returns:
7860: $count - integer count of the number of same characters between the
7861: two arguments
7862:
7863: =cut
7864:
7865: sub num_matches {
7866: my ($orig,$code) = @_;
7867: my @code=split(//,$code);
7868: my @orig=split(//,$orig);
7869: my $same=0;
7870: for (my $i=0;$i<scalar(@code);$i++) {
7871: if ($code[$i] eq $orig[$i]) { $same++; }
7872: }
7873: return $same;
7874: }
7875:
7876: =pod
7877:
7878: =item scantron_get_closely_matching_CODEs
7879:
7880: Cycles through all CODEs and finds the set that has the greatest
7881: number of same characters as the provided CODE
7882:
7883: Arguments:
7884: $allcodes - hash ref returned by &get_codes()
7885: $CODE - CODE from the current scanline
7886:
7887: Returns:
7888: 2 element list
7889: - first elements is number of how closely matching the best fit is
7890: (5 means best set has 5 matching characters)
7891: - second element is an arrary ref containing the set of valid CODEs
7892: that best fit the passed in CODE
7893:
7894: =cut
7895:
7896: sub scantron_get_closely_matching_CODEs {
7897: my ($allcodes,$CODE)=@_;
7898: my @CODEs;
7899: foreach my $testcode (sort(keys(%{$allcodes}))) {
7900: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7901: }
7902:
7903: return ($#CODEs,$CODEs[-1]);
7904: }
7905:
7906: =pod
7907:
7908: =item get_codes
7909:
7910: Builds a hash which has keys of all of the valid CODEs from the selected
7911: set of remembered CODEs.
7912:
7913: Arguments:
7914: $old_name - name of the set of remembered CODEs
7915: $cdom - domain of the course
7916: $cnum - internal course name
7917:
7918: Returns:
7919: %allcodes - keys are the valid CODEs, values are all 1
7920:
7921: =cut
7922:
7923: sub get_codes {
7924: my ($old_name, $cdom, $cnum) = @_;
7925: if (!$old_name) {
7926: $old_name=$env{'form.scantron_CODElist'};
7927: }
7928: if (!$cdom) {
7929: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7930: }
7931: if (!$cnum) {
7932: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7933: }
7934: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7935: $cdom,$cnum);
7936: my %allcodes;
7937: if ($result{"type\0$old_name"} eq 'number') {
7938: %allcodes=map {($_,1)} split(',',$result{$old_name});
7939: } else {
7940: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7941: }
7942: return %allcodes;
7943: }
7944:
7945: =pod
7946:
7947: =item scantron_validate_CODE
7948:
7949: Validates all scanlines in the selected file to not have any
7950: invalid or underspecified CODEs and that none of the codes are
7951: duplicated if this was requested.
7952:
7953: =cut
7954:
7955: sub scantron_validate_CODE {
7956: my ($r,$currentphase) = @_;
7957: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7958: if ($scantron_config{'CODElocation'} &&
7959: $scantron_config{'CODEstart'} &&
7960: $scantron_config{'CODElength'}) {
7961: if (!defined($env{'form.scantron_CODElist'})) {
7962: &FIXME_blow_up()
7963: }
7964: } else {
7965: return (0,$currentphase+1);
7966: }
7967:
7968: my %usedCODEs;
7969:
7970: my %allcodes=&get_codes();
7971:
7972: my $nav_error;
7973: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7974: if ($nav_error) {
7975: $r->print(&navmap_errormsg());
7976: return(1,$currentphase);
7977: }
7978:
7979: my ($scanlines,$scan_data)=&scantron_getfile();
7980: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7981: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7982: if ($line=~/^[\s\cz]*$/) { next; }
7983: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7984: $scan_data);
7985: my $CODE=$$scan_record{'scantron.CODE'};
7986: my $error=0;
7987: if (!&Apache::lonnet::validCODE($CODE)) {
7988: &scantron_get_correction($r,$i,$scan_record,
7989: \%scantron_config,
7990: $line,'incorrectCODE',\%allcodes);
7991: return(1,$currentphase);
7992: }
7993: if (%allcodes && !exists($allcodes{$CODE})
7994: && !$$scan_record{'scantron.useCODE'}) {
7995: &scantron_get_correction($r,$i,$scan_record,
7996: \%scantron_config,
7997: $line,'incorrectCODE',\%allcodes);
7998: return(1,$currentphase);
7999: }
8000: if (exists($usedCODEs{$CODE})
8001: && $env{'form.scantron_CODEunique'} eq 'yes'
8002: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
8003: &scantron_get_correction($r,$i,$scan_record,
8004: \%scantron_config,
8005: $line,'duplicateCODE',$usedCODEs{$CODE});
8006: return(1,$currentphase);
8007: }
8008: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
8009: }
8010: return (0,$currentphase+1);
8011: }
8012:
8013: =pod
8014:
8015: =item scantron_validate_doublebubble
8016:
8017: Validates all scanlines in the selected file to not have any
8018: bubble lines with multiple bubbles marked.
8019:
8020: =cut
8021:
8022: sub scantron_validate_doublebubble {
8023: my ($r,$currentphase) = @_;
8024: #get student info
8025: my $classlist=&Apache::loncoursedata::get_classlist();
8026: my %idmap=&username_to_idmap($classlist);
8027: my (undef,undef,$sequence)=
8028: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8029:
8030: #get scantron line setup
8031: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8032: my ($scanlines,$scan_data)=&scantron_getfile();
8033:
8034: my $navmap = Apache::lonnavmaps::navmap->new();
8035: unless (ref($navmap)) {
8036: $r->print(&navmap_errormsg());
8037: return(1,$currentphase);
8038: }
8039: my $map=$navmap->getResourceByUrl($sequence);
8040: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8041: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8042: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8043: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8044:
8045: my $nav_error;
8046: if (ref($map)) {
8047: $randomorder = $map->randomorder();
8048: $randompick = $map->randompick();
8049: if ($randomorder || $randompick) {
8050: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8051: if ($nav_error) {
8052: $r->print(&navmap_errormsg());
8053: return(1,$currentphase);
8054: }
8055: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8056: \%grader_randomlists_by_symb,$bubbles_per_row);
8057: }
8058: } else {
8059: $r->print(&navmap_errormsg());
8060: return(1,$currentphase);
8061: }
8062:
8063: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
8064: if ($nav_error) {
8065: $r->print(&navmap_errormsg());
8066: return(1,$currentphase);
8067: }
8068:
8069: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8070: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8071: if ($line=~/^[\s\cz]*$/) { next; }
8072: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8073: $scan_data,undef,\%idmap,$randomorder,
8074: $randompick,$sequence,\@master_seq,
8075: \%symb_to_resource,\%grader_partids_by_symb,
8076: \%orderedforcode,\%respnumlookup,\%startline);
8077: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
8078: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
8079: 'doublebubble',
8080: $$scan_record{'scantron.doubleerror'},
8081: $randomorder,$randompick,\%respnumlookup,\%startline);
8082: return (1,$currentphase);
8083: }
8084: return (0,$currentphase+1);
8085: }
8086:
8087:
8088: sub scantron_get_maxbubble {
8089: my ($nav_error,$scantron_config) = @_;
8090: if (defined($env{'form.scantron_maxbubble'}) &&
8091: $env{'form.scantron_maxbubble'}) {
8092: &restore_bubble_lines();
8093: return $env{'form.scantron_maxbubble'};
8094: }
8095:
8096: my (undef, undef, $sequence) =
8097: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8098:
8099: my $navmap=Apache::lonnavmaps::navmap->new();
8100: unless (ref($navmap)) {
8101: if (ref($nav_error)) {
8102: $$nav_error = 1;
8103: }
8104: return;
8105: }
8106: my $map=$navmap->getResourceByUrl($sequence);
8107: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8108: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8109:
8110: &Apache::lonxml::clear_problem_counter();
8111:
8112: my $uname = $env{'user.name'};
8113: my $udom = $env{'user.domain'};
8114: my $cid = $env{'request.course.id'};
8115: my $total_lines = 0;
8116: %bubble_lines_per_response = ();
8117: %first_bubble_line = ();
8118: %subdivided_bubble_lines = ();
8119: %responsetype_per_response = ();
8120: %masterseq_id_responsenum = ();
8121:
8122: my $response_number = 0;
8123: my $bubble_line = 0;
8124: foreach my $resource (@resources) {
8125: my $resid = $resource->id();
8126: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8127: $udom,undef,$bubbles_per_row);
8128: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8129: foreach my $part_id (@{$parts}) {
8130: my $lines;
8131:
8132: # TODO - make this a persistent hash not an array.
8133:
8134: # optionresponse, matchresponse and rankresponse type items
8135: # render as separate sub-questions in exam mode.
8136: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8137: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8138: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8139: my ($numbub,$numshown);
8140: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8141: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8142: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8143: }
8144: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8145: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8146: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8147: }
8148: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8149: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8150: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8151: }
8152: }
8153: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8154: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8155: }
8156: my $bubbles_per_row =
8157: &bubblesheet_bubbles_per_row($scantron_config);
8158: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8159: if (($numbub % $bubbles_per_row) != 0) {
8160: $inner_bubble_lines++;
8161: }
8162: for (my $i=0; $i<$numshown; $i++) {
8163: $subdivided_bubble_lines{$response_number} .=
8164: $inner_bubble_lines.',';
8165: }
8166: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8167: $lines = $numshown * $inner_bubble_lines;
8168: } else {
8169: $lines = $analysis->{"$part_id.bubble_lines"};
8170: }
8171:
8172: $first_bubble_line{$response_number} = $bubble_line;
8173: $bubble_lines_per_response{$response_number} = $lines;
8174: $responsetype_per_response{$response_number} =
8175: $analysis->{$part_id.'.type'};
8176: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8177: $response_number++;
8178:
8179: $bubble_line += $lines;
8180: $total_lines += $lines;
8181: }
8182: }
8183: }
8184: &Apache::lonnet::delenv('scantron.');
8185:
8186: &save_bubble_lines();
8187: $env{'form.scantron_maxbubble'} =
8188: $total_lines;
8189: return $env{'form.scantron_maxbubble'};
8190: }
8191:
8192: sub bubblesheet_bubbles_per_row {
8193: my ($scantron_config) = @_;
8194: my $bubbles_per_row;
8195: if (ref($scantron_config) eq 'HASH') {
8196: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8197: }
8198: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8199: $bubbles_per_row = 10;
8200: }
8201: return $bubbles_per_row;
8202: }
8203:
8204: sub scantron_validate_missingbubbles {
8205: my ($r,$currentphase) = @_;
8206: #get student info
8207: my $classlist=&Apache::loncoursedata::get_classlist();
8208: my %idmap=&username_to_idmap($classlist);
8209: my (undef,undef,$sequence)=
8210: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8211:
8212: #get scantron line setup
8213: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8214: my ($scanlines,$scan_data)=&scantron_getfile();
8215:
8216: my $navmap = Apache::lonnavmaps::navmap->new();
8217: unless (ref($navmap)) {
8218: $r->print(&navmap_errormsg());
8219: return(1,$currentphase);
8220: }
8221:
8222: my $map=$navmap->getResourceByUrl($sequence);
8223: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8224: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8225: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8226: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8227:
8228: my $nav_error;
8229: if (ref($map)) {
8230: $randomorder = $map->randomorder();
8231: $randompick = $map->randompick();
8232: if ($randomorder || $randompick) {
8233: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8234: if ($nav_error) {
8235: $r->print(&navmap_errormsg());
8236: return(1,$currentphase);
8237: }
8238: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8239: \%grader_randomlists_by_symb,$bubbles_per_row);
8240: }
8241: } else {
8242: $r->print(&navmap_errormsg());
8243: return(1,$currentphase);
8244: }
8245:
8246:
8247: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8248: if ($nav_error) {
8249: $r->print(&navmap_errormsg());
8250: return(1,$currentphase);
8251: }
8252:
8253: if (!$max_bubble) { $max_bubble=2**31; }
8254: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8255: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8256: if ($line=~/^[\s\cz]*$/) { next; }
8257: my $scan_record =
8258: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8259: $randomorder,$randompick,$sequence,\@master_seq,
8260: \%symb_to_resource,\%grader_partids_by_symb,
8261: \%orderedforcode,\%respnumlookup,\%startline);
8262: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8263: my @to_correct;
8264:
8265: # Probably here's where the error is...
8266:
8267: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8268: my $lastbubble;
8269: if ($missing =~ /^(\d+)\.(\d+)$/) {
8270: my $question = $1;
8271: my $subquestion = $2;
8272: my ($first,$responsenum);
8273: if ($randomorder || $randompick) {
8274: $responsenum = $respnumlookup{$question-1};
8275: $first = $startline{$question-1};
8276: } else {
8277: $responsenum = $question-1;
8278: $first = $first_bubble_line{$responsenum};
8279: }
8280: if (!defined($first)) { next; }
8281: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8282: my $subcount = 1;
8283: while ($subcount<$subquestion) {
8284: $first += $subans[$subcount-1];
8285: $subcount ++;
8286: }
8287: my $count = $subans[$subquestion-1];
8288: $lastbubble = $first + $count;
8289: } else {
8290: my ($first,$responsenum);
8291: if ($randomorder || $randompick) {
8292: $responsenum = $respnumlookup{$missing-1};
8293: $first = $startline{$missing-1};
8294: } else {
8295: $responsenum = $missing-1;
8296: $first = $first_bubble_line{$responsenum};
8297: }
8298: if (!defined($first)) { next; }
8299: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8300: }
8301: if ($lastbubble > $max_bubble) { next; }
8302: push(@to_correct,$missing);
8303: }
8304: if (@to_correct) {
8305: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8306: $line,'missingbubble',\@to_correct,
8307: $randomorder,$randompick,\%respnumlookup,
8308: \%startline);
8309: return (1,$currentphase);
8310: }
8311:
8312: }
8313: return (0,$currentphase+1);
8314: }
8315:
8316: sub hand_bubble_option {
8317: my (undef, undef, $sequence) =
8318: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8319: return if ($sequence eq '');
8320: my $navmap = Apache::lonnavmaps::navmap->new();
8321: unless (ref($navmap)) {
8322: return;
8323: }
8324: my $needs_hand_bubbles;
8325: my $map=$navmap->getResourceByUrl($sequence);
8326: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8327: foreach my $res (@resources) {
8328: if (ref($res)) {
8329: if ($res->is_problem()) {
8330: my $partlist = $res->parts();
8331: foreach my $part (@{ $partlist }) {
8332: my @types = $res->responseType($part);
8333: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8334: $needs_hand_bubbles = 1;
8335: last;
8336: }
8337: }
8338: }
8339: }
8340: }
8341: if ($needs_hand_bubbles) {
8342: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8343: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8344: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8345: &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 />').
8346: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8347: '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
8348: }
8349: return;
8350: }
8351:
8352: sub scantron_process_students {
8353: my ($r) = @_;
8354:
8355: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8356: my ($symb)=&get_symb($r);
8357: if (!$symb) {
8358: return '';
8359: }
8360: my $default_form_data=&defaultFormData($symb);
8361:
8362: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8363: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8364: my ($scanlines,$scan_data)=&scantron_getfile();
8365: my $classlist=&Apache::loncoursedata::get_classlist();
8366: my %idmap=&username_to_idmap($classlist);
8367: my $navmap=Apache::lonnavmaps::navmap->new();
8368: unless (ref($navmap)) {
8369: $r->print(&navmap_errormsg());
8370: return '';
8371: }
8372: my $map=$navmap->getResourceByUrl($sequence);
8373: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8374: %grader_randomlists_by_symb);
8375: if (ref($map)) {
8376: $randomorder = $map->randomorder();
8377: $randompick = $map->randompick();
8378: } else {
8379: $r->print(&navmap_errormsg());
8380: return '';
8381: }
8382: my $nav_error;
8383: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8384: my (%grader_partids_by_symb,%grader_randomlists_by_symb,%ordered);
8385: if ($randomorder || $randompick) {
8386: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8387: if ($nav_error) {
8388: $r->print(&navmap_errormsg());
8389: return '';
8390: }
8391: }
8392: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8393: \%grader_randomlists_by_symb,$bubbles_per_row);
8394:
8395: my ($uname,$udom);
8396: my $result= <<SCANTRONFORM;
8397: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8398: <input type="hidden" name="command" value="scantron_configphase" />
8399: $default_form_data
8400: SCANTRONFORM
8401: $r->print($result);
8402:
8403: my @delayqueue;
8404: my (%completedstudents,%scandata);
8405:
8406: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8407: my $count=&get_todo_count($scanlines,$scan_data);
8408: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8409: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8410: 'Processing first student');
8411: $r->print('<br />');
8412: my $start=&Time::HiRes::time();
8413: my $i=-1;
8414: my $started;
8415:
8416: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8417: if ($nav_error) {
8418: $r->print(&navmap_errormsg());
8419: return '';
8420: }
8421:
8422: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8423: # the user and return.
8424:
8425: if ($ssi_error) {
8426: $r->print("</form>");
8427: &ssi_print_error($r);
8428: $r->print(&show_grading_menu_form($symb));
8429: &Apache::lonnet::remove_lock($lock);
8430: return ''; # Dunno why the other returns return '' rather than just returning.
8431: }
8432:
8433: my %lettdig = &letter_to_digits();
8434: my $numletts = scalar(keys(%lettdig));
8435: my %orderedforcode;
8436:
8437: while ($i<$scanlines->{'count'}) {
8438: ($uname,$udom)=('','');
8439: $i++;
8440: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8441: if ($line=~/^[\s\cz]*$/) { next; }
8442: if ($started) {
8443: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8444: 'last student');
8445: }
8446: $started=1;
8447: my %respnumlookup = ();
8448: my %startline = ();
8449: my $total;
8450: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8451: $scan_data,undef,\%idmap,$randomorder,
8452: $randompick,$sequence,\@master_seq,
8453: \%symb_to_resource,\%grader_partids_by_symb,
8454: \%orderedforcode,\%respnumlookup,\%startline,
8455: \$total);
8456: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8457: \%idmap,$i)) {
8458: &scantron_add_delay(\@delayqueue,$line,
8459: 'Unable to find a student that matches',1);
8460: next;
8461: }
8462: if (exists $completedstudents{$uname}) {
8463: &scantron_add_delay(\@delayqueue,$line,
8464: 'Student '.$uname.' has multiple sheets',2);
8465: next;
8466: }
8467: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8468: my $user = $uname.':'.$usec;
8469: ($uname,$udom)=split(/:/,$uname);
8470:
8471: my $scancode;
8472: if ((exists($scan_record->{'scantron.CODE'})) &&
8473: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8474: $scancode = $scan_record->{'scantron.CODE'};
8475: } else {
8476: $scancode = '';
8477: }
8478:
8479: my @mapresources = @resources;
8480: if ($randomorder || $randompick) {
8481: @mapresources =
8482: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8483: \%orderedforcode);
8484: }
8485: my (%partids_by_symb,$res_error);
8486: foreach my $resource (@mapresources) {
8487: my $ressymb;
8488: if (ref($resource)) {
8489: $ressymb = $resource->symb();
8490: } else {
8491: $res_error = 1;
8492: last;
8493: }
8494: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8495: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8496: my ($analysis,$parts) =
8497: &scantron_partids_tograde($resource,$env{'request.course.id'},
8498: $uname,$udom,undef,$bubbles_per_row);
8499: $partids_by_symb{$ressymb} = $parts;
8500: } else {
8501: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8502: }
8503: }
8504:
8505: if ($res_error) {
8506: &scantron_add_delay(\@delayqueue,$line,
8507: 'An error occurred while grading student '.$uname,2);
8508: next;
8509: }
8510:
8511: &Apache::lonxml::clear_problem_counter();
8512: &Apache::lonnet::appenv($scan_record);
8513:
8514: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8515: &scantron_putfile($scanlines,$scan_data);
8516: }
8517:
8518: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8519: \@mapresources,\%partids_by_symb,
8520: $bubbles_per_row,$randomorder,$randompick,
8521: \%respnumlookup,\%startline)
8522: eq 'ssi_error') {
8523: $ssi_error = 0; # So end of handler error message does not trigger.
8524: $r->print("</form>");
8525: &ssi_print_error($r);
8526: $r->print(&show_grading_menu_form($symb));
8527: &Apache::lonnet::remove_lock($lock);
8528: return ''; # Why return ''? Beats me.
8529: }
8530:
8531: if (($scancode) && ($randomorder || $randompick)) {
8532: my $parmresult =
8533: &Apache::lonparmset::storeparm_by_symb($symb,
8534: '0_examcode',2,$scancode,
8535: 'string_examcode',$uname,
8536: $udom);
8537: }
8538: $completedstudents{$uname}={'line'=>$line};
8539: if ($env{'form.verifyrecord'}) {
8540: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8541: if ($randompick) {
8542: if ($total) {
8543: $lastpos = $total*$scantron_config{'Qlength'};
8544: }
8545: }
8546:
8547: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8548: chomp($studentdata);
8549: $studentdata =~ s/\r$//;
8550: my $studentrecord = '';
8551: my $counter = -1;
8552: foreach my $resource (@mapresources) {
8553: my $ressymb = $resource->symb();
8554: ($counter,my $recording) =
8555: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8556: $counter,$studentdata,$partids_by_symb{$ressymb},
8557: \%scantron_config,\%lettdig,$numletts,$randomorder,
8558: $randompick,\%respnumlookup,\%startline);
8559: $studentrecord .= $recording;
8560: }
8561: if ($studentrecord ne $studentdata) {
8562: &Apache::lonxml::clear_problem_counter();
8563: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8564: \@mapresources,\%partids_by_symb,
8565: $bubbles_per_row,$randomorder,$randompick,
8566: \%respnumlookup,\%startline)
8567: eq 'ssi_error') {
8568: $ssi_error = 0; # So end of handler error message does not trigger.
8569: $r->print("</form>");
8570: &ssi_print_error($r);
8571: $r->print(&show_grading_menu_form($symb));
8572: &Apache::lonnet::remove_lock($lock);
8573: delete($completedstudents{$uname});
8574: return '';
8575: }
8576: $counter = -1;
8577: $studentrecord = '';
8578: foreach my $resource (@mapresources) {
8579: my $ressymb = $resource->symb();
8580: ($counter,my $recording) =
8581: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8582: $counter,$studentdata,$partids_by_symb{$ressymb},
8583: \%scantron_config,\%lettdig,$numletts,
8584: $randomorder,$randompick,\%respnumlookup,
8585: \%startline);
8586: $studentrecord .= $recording;
8587: }
8588: if ($studentrecord ne $studentdata) {
8589: $r->print('<p><span class="LC_warning">');
8590: if ($scancode eq '') {
8591: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8592: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8593: } else {
8594: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8595: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8596: }
8597: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8598: &Apache::loncommon::start_data_table_header_row()."\n".
8599: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8600: &Apache::loncommon::end_data_table_header_row()."\n".
8601: &Apache::loncommon::start_data_table_row().
8602: '<td>'.&mt('Bubblesheet').'</td>'.
8603: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
8604: &Apache::loncommon::end_data_table_row().
8605: &Apache::loncommon::start_data_table_row().
8606: '<td>'.&mt('Stored submissions').'</td>'.
8607: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
8608: &Apache::loncommon::end_data_table_row().
8609: &Apache::loncommon::end_data_table().'</p>');
8610: } else {
8611: $r->print('<br /><span class="LC_warning">'.
8612: &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 />'.
8613: &mt("As a consequence, this user's submission history records two tries.").
8614: '</span><br />');
8615: }
8616: }
8617: }
8618: if (&Apache::loncommon::connection_aborted($r)) { last; }
8619: } continue {
8620: &Apache::lonxml::clear_problem_counter();
8621: &Apache::lonnet::delenv('scantron.');
8622: }
8623: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8624: &Apache::lonnet::remove_lock($lock);
8625: # my $lasttime = &Time::HiRes::time()-$start;
8626: # $r->print("<p>took $lasttime</p>");
8627:
8628: $r->print("</form>");
8629: $r->print(&show_grading_menu_form($symb));
8630: return '';
8631: }
8632:
8633: sub graders_resources_pass {
8634: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8635: $bubbles_per_row) = @_;
8636: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8637: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8638: foreach my $resource (@{$resources}) {
8639: my $ressymb = $resource->symb();
8640: my ($analysis,$parts) =
8641: &scantron_partids_tograde($resource,$env{'request.course.id'},
8642: $env{'user.name'},$env{'user.domain'},
8643: 1,$bubbles_per_row);
8644: $grader_partids_by_symb->{$ressymb} = $parts;
8645: if (ref($analysis) eq 'HASH') {
8646: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8647: $grader_randomlists_by_symb->{$ressymb} =
8648: $analysis->{'parts_withrandomlist'};
8649: }
8650: }
8651: }
8652: }
8653: return;
8654: }
8655:
8656: =pod
8657:
8658: =item users_order
8659:
8660: Returns array of resources in current map, ordered based on either CODE,
8661: if this is a CODEd exam, or based on student's identity if this is a
8662: "NAMEd" exam.
8663:
8664: Should be used when randomorder and/or randompick applied when the
8665: corresponding exam was printed, prior to students completing bubblesheets
8666: for the version of the exam the student received.
8667:
8668: =cut
8669:
8670: sub users_order {
8671: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8672: my @mapresources;
8673: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8674: return @mapresources;
8675: }
8676: if ($scancode) {
8677: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8678: @mapresources = @{$orderedforcode->{$scancode}};
8679: } else {
8680: $env{'form.CODE'} = $scancode;
8681: my $actual_seq =
8682: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8683: $master_seq,
8684: $user,$scancode,1);
8685: if (ref($actual_seq) eq 'ARRAY') {
8686: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8687: if (ref($orderedforcode) eq 'HASH') {
8688: if (@mapresources > 0) {
8689: $orderedforcode->{$scancode} = \@mapresources;
8690: }
8691: }
8692: }
8693: delete($env{'form.CODE'});
8694: }
8695: } else {
8696: my $actual_seq =
8697: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8698: $master_seq,
8699: $user,undef,1);
8700: if (ref($actual_seq) eq 'ARRAY') {
8701: @mapresources =
8702: map { $symb_to_resource->{$_}; } @{$actual_seq};
8703: }
8704: }
8705: return @mapresources;
8706: }
8707:
8708: sub grade_student_bubbles {
8709: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8710: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8711: my $uselookup = 0;
8712: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8713: (ref($startline) eq 'HASH')) {
8714: $uselookup = 1;
8715: }
8716:
8717: if (ref($resources) eq 'ARRAY') {
8718: my $count = 0;
8719: foreach my $resource (@{$resources}) {
8720: my $ressymb = $resource->symb();
8721: my %form = ('submitted' => 'scantron',
8722: 'grade_target' => 'grade',
8723: 'grade_username' => $uname,
8724: 'grade_domain' => $udom,
8725: 'grade_courseid' => $env{'request.course.id'},
8726: 'grade_symb' => $ressymb,
8727: 'CODE' => $scancode
8728: );
8729: if ($bubbles_per_row ne '') {
8730: $form{'bubbles_per_row'} = $bubbles_per_row;
8731: }
8732: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8733: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8734: }
8735: if (ref($parts) eq 'HASH') {
8736: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8737: foreach my $part (@{$parts->{$ressymb}}) {
8738: if ($uselookup) {
8739: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8740: } else {
8741: $form{'scantron_questnum_start.'.$part} =
8742: 1+$env{'form.scantron.first_bubble_line.'.$count};
8743: }
8744: $count++;
8745: }
8746: }
8747: }
8748: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8749: return 'ssi_error' if ($ssi_error);
8750: last if (&Apache::loncommon::connection_aborted($r));
8751: }
8752: }
8753: return;
8754: }
8755:
8756: sub scantron_upload_scantron_data {
8757: my ($r)=@_;
8758: my $dom = $env{'request.role.domain'};
8759: my $domdesc = &Apache::lonnet::domain($dom,'description');
8760: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8761: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8762: 'domainid',
8763: 'coursename',$dom);
8764: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8765: (' 'x2).&mt('(shows course personnel)');
8766: my ($symb) = &get_symb($r,1);
8767: my $default_form_data=&defaultFormData($symb);
8768: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8769: 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.");
8770: $r->print('
8771: <script type="text/javascript" language="javascript">
8772: function checkUpload(formname) {
8773: if (formname.upfile.value == "") {
8774: alert("'.$nofile_alert.'");
8775: return false;
8776: }
8777: if (formname.courseid.value == "") {
8778: alert("'.$nocourseid_alert.'");
8779: return false;
8780: }
8781: formname.submit();
8782: }
8783:
8784: function ToSyllabus() {
8785: var cdom = '."'$dom'".';
8786: var cnum = document.rules.courseid.value;
8787: if (cdom == "" || cdom == null) {
8788: return;
8789: }
8790: if (cnum == "" || cnum == null) {
8791: return;
8792: }
8793: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8794: "height=350,width=350,scrollbars=yes,menubar=no");
8795: return;
8796: }
8797:
8798: </script>
8799:
8800: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8801:
8802: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8803: '.$default_form_data.
8804: &Apache::lonhtmlcommon::start_pick_box().
8805: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8806: '<input name="courseid" type="text" size="30" />'.$select_link.
8807: &Apache::lonhtmlcommon::row_closure().
8808: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8809: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8810: &Apache::lonhtmlcommon::row_closure().
8811: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8812: '<input name="domainid" type="hidden" />'.$domdesc.
8813: &Apache::lonhtmlcommon::row_closure().
8814: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8815: '<input type="file" name="upfile" size="50" />'.
8816: &Apache::lonhtmlcommon::row_closure(1).
8817: &Apache::lonhtmlcommon::end_pick_box().'<br />
8818:
8819: <input name="command" value="scantronupload_save" type="hidden" />
8820: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8821: </form>
8822: ');
8823: return '';
8824: }
8825:
8826:
8827: sub scantron_upload_scantron_data_save {
8828: my($r)=@_;
8829: my ($symb)=&get_symb($r,1);
8830: my $doanotherupload=
8831: '<br /><form action="/adm/grades" method="post">'."\n".
8832: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8833: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8834: '</form>'."\n";
8835: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8836: !&Apache::lonnet::allowed('usc',
8837: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8838: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8839: if ($symb) {
8840: $r->print(&show_grading_menu_form($symb));
8841: } else {
8842: $r->print($doanotherupload);
8843: }
8844: return '';
8845: }
8846: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8847: my $uploadedfile;
8848: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
8849: if (length($env{'form.upfile'}) < 2) {
8850: $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8851: } else {
8852: my $result =
8853: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8854: $env{'form.courseid'},$env{'form.domainid'});
8855: if ($result =~ m{^/uploaded/}) {
8856: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
8857: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
8858: '<span class="LC_filename">'.$result.'</span>'));
8859: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8860: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8861: $env{'form.courseid'},$uploadedfile));
8862: } else {
8863: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
8864: '<span class="LC_error">','</span>',$result,
8865: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8866: }
8867: }
8868: if ($symb) {
8869: $r->print(&scantron_selectphase($r,$uploadedfile));
8870: } else {
8871: $r->print($doanotherupload);
8872: }
8873: return '';
8874: }
8875:
8876: sub validate_uploaded_scantron_file {
8877: my ($cdom,$cname,$fname) = @_;
8878: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8879: my @lines;
8880: if ($scanlines ne '-1') {
8881: @lines=split("\n",$scanlines,-1);
8882: }
8883: my $output;
8884: if (@lines) {
8885: my (%counts,$max_match_format);
8886: my ($max_match_count,$max_match_pct) = (0,0);
8887: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8888: my %idmap = &username_to_idmap($classlist);
8889: foreach my $key (keys(%idmap)) {
8890: my $lckey = lc($key);
8891: $idmap{$lckey} = $idmap{$key};
8892: }
8893: my %unique_formats;
8894: my @formatlines = &get_scantronformat_file();
8895: foreach my $line (@formatlines) {
8896: chomp($line);
8897: my @config = split(/:/,$line);
8898: my $idstart = $config[5];
8899: my $idlength = $config[6];
8900: if (($idstart ne '') && ($idlength > 0)) {
8901: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8902: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8903: } else {
8904: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8905: }
8906: }
8907: }
8908: foreach my $key (keys(%unique_formats)) {
8909: my ($idstart,$idlength) = split(':',$key);
8910: %{$counts{$key}} = (
8911: 'found' => 0,
8912: 'total' => 0,
8913: );
8914: foreach my $line (@lines) {
8915: next if ($line =~ /^#/);
8916: next if ($line =~ /^[\s\cz]*$/);
8917: my $id = substr($line,$idstart-1,$idlength);
8918: $id = lc($id);
8919: if (exists($idmap{$id})) {
8920: $counts{$key}{'found'} ++;
8921: }
8922: $counts{$key}{'total'} ++;
8923: }
8924: if ($counts{$key}{'total'}) {
8925: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8926: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8927: $max_match_pct = $percent_match;
8928: $max_match_format = $key;
8929: $max_match_count = $counts{$key}{'total'};
8930: }
8931: }
8932: }
8933: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8934: my $format_descs;
8935: my $numwithformat = @{$unique_formats{$max_match_format}};
8936: for (my $i=0; $i<$numwithformat; $i++) {
8937: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8938: if ($i<$numwithformat-2) {
8939: $format_descs .= '"<i>'.$desc.'</i>", ';
8940: } elsif ($i==$numwithformat-2) {
8941: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8942: } elsif ($i==$numwithformat-1) {
8943: $format_descs .= '"<i>'.$desc.'</i>"';
8944: }
8945: }
8946: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8947: $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8948: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8949: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8950: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8951: '<i>'.$cdom.'</i>').'</li>'.
8952: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8953: '<li>'.&mt('The course roster is not up to date').'</li>'.
8954: '</ul>';
8955: }
8956: } else {
8957: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8958: }
8959: return $output;
8960: }
8961:
8962: sub valid_file {
8963: my ($requested_file)=@_;
8964: foreach my $filename (sort(&scantron_filenames())) {
8965: if ($requested_file eq $filename) { return 1; }
8966: }
8967: return 0;
8968: }
8969:
8970: sub scantron_download_scantron_data {
8971: my ($r)=@_;
8972: my ($symb) = &get_symb($r,1);
8973: my $default_form_data=&defaultFormData($symb);
8974: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8975: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8976: my $file=$env{'form.scantron_selectfile'};
8977: if (! &valid_file($file)) {
8978: $r->print('
8979: <p>
8980: '.&mt('The requested filename was invalid.').'
8981: </p>
8982: ');
8983: $r->print(&show_grading_menu_form($symb));
8984: return;
8985: }
8986: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8987: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8988: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8989: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8990: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8991: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8992: $r->print('
8993: <p>
8994: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8995: '<a href="'.$orig.'">','</a>').'
8996: </p>
8997: <p>
8998: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8999: '<a href="'.$corrected.'">','</a>').'
9000: </p>
9001: <p>
9002: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
9003: '<a href="'.$skipped.'">','</a>').'
9004: </p>
9005: ');
9006: $r->print(&show_grading_menu_form($symb));
9007: return '';
9008: }
9009:
9010: sub checkscantron_results {
9011: my ($r) = @_;
9012: my ($symb)=&get_symb($r);
9013: if (!$symb) {return '';}
9014: my $grading_menu_button=&show_grading_menu_form($symb);
9015: my $cid = $env{'request.course.id'};
9016: my %lettdig = &letter_to_digits();
9017: my $numletts = scalar(keys(%lettdig));
9018: my $cnum = $env{'course.'.$cid.'.num'};
9019: my $cdom = $env{'course.'.$cid.'.domain'};
9020: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
9021: my %record;
9022: my %scantron_config =
9023: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
9024: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
9025: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
9026: my $classlist=&Apache::loncoursedata::get_classlist();
9027: my %idmap=&Apache::grades::username_to_idmap($classlist);
9028: my $navmap=Apache::lonnavmaps::navmap->new();
9029: unless (ref($navmap)) {
9030: $r->print(&navmap_errormsg());
9031: return '';
9032: }
9033: my $map=$navmap->getResourceByUrl($sequence);
9034: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
9035: %grader_randomlists_by_symb,%orderedforcode);
9036: if (ref($map)) {
9037: $randomorder=$map->randomorder();
9038: $randompick=$map->randompick();
9039: }
9040: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
9041: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
9042: if ($nav_error) {
9043: $r->print(&navmap_errormsg());
9044: return '';
9045: }
9046: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
9047: \%grader_randomlists_by_symb,$bubbles_per_row);
9048: my ($uname,$udom);
9049: my (%scandata,%lastname,%bylast);
9050: $r->print('
9051: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
9052:
9053: my @delayqueue;
9054: my %completedstudents;
9055:
9056: my $count=&get_todo_count($scanlines,$scan_data);
9057: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
9058: my ($username,$domain,$started,%ordered);
9059: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
9060: if ($nav_error) {
9061: $r->print(&navmap_errormsg());
9062: return '';
9063: }
9064:
9065: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
9066: 'Processing first student');
9067: my $start=&Time::HiRes::time();
9068: my $i=-1;
9069:
9070: while ($i<$scanlines->{'count'}) {
9071: ($username,$domain,$uname)=('','','');
9072: $i++;
9073: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
9074: if ($line=~/^[\s\cz]*$/) { next; }
9075: if ($started) {
9076: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
9077: 'last student');
9078: }
9079: $started=1;
9080: my $scan_record=
9081: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9082: $scan_data);
9083: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9084: \%idmap,$i)) {
9085: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9086: 'Unable to find a student that matches',1);
9087: next;
9088: }
9089: if (exists $completedstudents{$uname}) {
9090: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9091: 'Student '.$uname.' has multiple sheets',2);
9092: next;
9093: }
9094: my $pid = $scan_record->{'scantron.ID'};
9095: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9096: push(@{$bylast{$lastname{$pid}}},$pid);
9097: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9098: my $user = $uname.':'.$usec;
9099: ($username,$domain)=split(/:/,$uname);
9100:
9101: my $scancode;
9102: if ((exists($scan_record->{'scantron.CODE'})) &&
9103: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9104: $scancode = $scan_record->{'scantron.CODE'};
9105: } else {
9106: $scancode = '';
9107: }
9108:
9109: my @mapresources = @resources;
9110: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9111: my %respnumlookup=();
9112: my %startline=();
9113: if ($randomorder || $randompick) {
9114: @mapresources =
9115: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9116: \%orderedforcode);
9117: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9118: $scan_record,\@master_seq,\%symb_to_resource,
9119: \%grader_partids_by_symb,\%orderedforcode,
9120: \%respnumlookup,\%startline);
9121: if ($randompick && $total) {
9122: $lastpos = $total*$scantron_config{'Qlength'};
9123: }
9124: }
9125: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9126: chomp($scandata{$pid});
9127: $scandata{$pid} =~ s/\r$//;
9128:
9129: my $counter = -1;
9130: foreach my $resource (@mapresources) {
9131: my $parts;
9132: my $ressymb = $resource->symb();
9133: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9134: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9135: (my $analysis,$parts) =
9136: &scantron_partids_tograde($resource,$env{'request.course.id'},
9137: $username,$domain,undef,
9138: $bubbles_per_row);
9139: } else {
9140: $parts = $grader_partids_by_symb{$ressymb};
9141: }
9142: ($counter,my $recording) =
9143: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9144: $scandata{$pid},$parts,
9145: \%scantron_config,\%lettdig,$numletts,
9146: $randomorder,$randompick,
9147: \%respnumlookup,\%startline);
9148: $record{$pid} .= $recording;
9149: }
9150: }
9151: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9152: $r->print('<br />');
9153: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9154: $passed = 0;
9155: $failed = 0;
9156: $numstudents = 0;
9157: foreach my $last (sort(keys(%bylast))) {
9158: if (ref($bylast{$last}) eq 'ARRAY') {
9159: foreach my $pid (sort(@{$bylast{$last}})) {
9160: my $showscandata = $scandata{$pid};
9161: my $showrecord = $record{$pid};
9162: $showscandata =~ s/\s/ /g;
9163: $showrecord =~ s/\s/ /g;
9164: if ($scandata{$pid} eq $record{$pid}) {
9165: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9166: $okstudents .= '<tr class="'.$css_class.'">'.
9167: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9168: '</tr>'."\n".
9169: '<tr class="'.$css_class.'">'."\n".
9170: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
9171: $passed ++;
9172: } else {
9173: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9174: $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".
9175: '</tr>'."\n".
9176: '<tr class="'.$css_class.'">'."\n".
9177: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9178: '</tr>'."\n";
9179: $failed ++;
9180: }
9181: $numstudents ++;
9182: }
9183: }
9184: }
9185: $r->print('<p>'.
9186: &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).',
9187: '<b>',
9188: $numstudents,
9189: '</b>',
9190: $env{'form.scantron_maxbubble'}).
9191: '</p>'
9192: );
9193: $r->print('<p>'
9194: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9195: .'<br />'
9196: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9197: .'</p>');
9198: if ($passed) {
9199: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9200: $r->print(&Apache::loncommon::start_data_table()."\n".
9201: &Apache::loncommon::start_data_table_header_row()."\n".
9202: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9203: &Apache::loncommon::end_data_table_header_row()."\n".
9204: $okstudents."\n".
9205: &Apache::loncommon::end_data_table().'<br />');
9206: }
9207: if ($failed) {
9208: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9209: $r->print(&Apache::loncommon::start_data_table()."\n".
9210: &Apache::loncommon::start_data_table_header_row()."\n".
9211: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9212: &Apache::loncommon::end_data_table_header_row()."\n".
9213: $badstudents."\n".
9214: &Apache::loncommon::end_data_table()).'<br />'.
9215: &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.');
9216: }
9217: $r->print('</form><br />'.$grading_menu_button);
9218: return;
9219: }
9220:
9221: sub verify_scantron_grading {
9222: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9223: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9224: $respnumlookup,$startline) = @_;
9225: my ($record,%expected,%startpos);
9226: return ($counter,$record) if (!ref($resource));
9227: return ($counter,$record) if (!$resource->is_problem());
9228: my $symb = $resource->symb();
9229: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9230: foreach my $part_id (@{$partids}) {
9231: $counter ++;
9232: $expected{$part_id} = 0;
9233: my $respnum = $counter;
9234: if ($randomorder || $randompick) {
9235: $respnum = $respnumlookup->{$counter};
9236: $startpos{$part_id} = $startline->{$counter} + 1;
9237: } else {
9238: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9239: }
9240: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9241: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9242: foreach my $item (@sub_lines) {
9243: $expected{$part_id} += $item;
9244: }
9245: } else {
9246: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9247: }
9248: }
9249: if ($symb) {
9250: my %recorded;
9251: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9252: if ($returnhash{'version'}) {
9253: my %lasthash=();
9254: my $version;
9255: for ($version=1;$version<=$returnhash{'version'};$version++) {
9256: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9257: $lasthash{$key}=$returnhash{$version.':'.$key};
9258: }
9259: }
9260: foreach my $key (keys(%lasthash)) {
9261: if ($key =~ /\.scantron$/) {
9262: my $value = &unescape($lasthash{$key});
9263: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9264: if ($value eq '') {
9265: for (my $i=0; $i<$expected{$part_id}; $i++) {
9266: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9267: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9268: }
9269: }
9270: } else {
9271: my @tocheck;
9272: my @items = split(//,$value);
9273: if (($scantron_config->{'Qon'} eq 'letter') ||
9274: ($scantron_config->{'Qon'} eq 'number')) {
9275: if (@items < $expected{$part_id}) {
9276: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9277: my @singles = split(//,$fragment);
9278: foreach my $pos (@singles) {
9279: if ($pos eq ' ') {
9280: push(@tocheck,$pos);
9281: } else {
9282: my $next = shift(@items);
9283: push(@tocheck,$next);
9284: }
9285: }
9286: } else {
9287: @tocheck = @items;
9288: }
9289: foreach my $letter (@tocheck) {
9290: if ($scantron_config->{'Qon'} eq 'letter') {
9291: if ($letter !~ /^[A-J]$/) {
9292: $letter = $scantron_config->{'Qoff'};
9293: }
9294: $recorded{$part_id} .= $letter;
9295: } elsif ($scantron_config->{'Qon'} eq 'number') {
9296: my $digit;
9297: if ($letter !~ /^[A-J]$/) {
9298: $digit = $scantron_config->{'Qoff'};
9299: } else {
9300: $digit = $lettdig->{$letter};
9301: }
9302: $recorded{$part_id} .= $digit;
9303: }
9304: }
9305: } else {
9306: @tocheck = @items;
9307: for (my $i=0; $i<$expected{$part_id}; $i++) {
9308: my $curr_sub = shift(@tocheck);
9309: my $digit;
9310: if ($curr_sub =~ /^[A-J]$/) {
9311: $digit = $lettdig->{$curr_sub}-1;
9312: }
9313: if ($curr_sub eq 'J') {
9314: $digit += scalar($numletts);
9315: }
9316: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9317: if ($j == $digit) {
9318: $recorded{$part_id} .= $scantron_config->{'Qon'};
9319: } else {
9320: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9321: }
9322: }
9323: }
9324: }
9325: }
9326: }
9327: }
9328: }
9329: foreach my $part_id (@{$partids}) {
9330: if ($recorded{$part_id} eq '') {
9331: for (my $i=0; $i<$expected{$part_id}; $i++) {
9332: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9333: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9334: }
9335: }
9336: }
9337: $record .= $recorded{$part_id};
9338: }
9339: }
9340: return ($counter,$record);
9341: }
9342:
9343: sub letter_to_digits {
9344: my %lettdig = (
9345: A => 1,
9346: B => 2,
9347: C => 3,
9348: D => 4,
9349: E => 5,
9350: F => 6,
9351: G => 7,
9352: H => 8,
9353: I => 9,
9354: J => 0,
9355: );
9356: return %lettdig;
9357: }
9358:
9359:
9360: #-------- end of section for handling grading scantron forms -------
9361: #
9362: #-------------------------------------------------------------------
9363:
9364: #-------------------------- Menu interface -------------------------
9365: #
9366: #--- Show a Grading Menu button - Calls the next routine ---
9367: sub show_grading_menu_form {
9368: my ($symb)=@_;
9369: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
9370: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9371: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
9372: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
9373: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
9374: '</form>'."\n";
9375: return $result;
9376: }
9377:
9378: # -- Retrieve choices for grading form
9379: sub savedState {
9380: my %savedState = ();
9381: if ($env{'form.saveState'}) {
9382: foreach (split(/:/,$env{'form.saveState'})) {
9383: my ($key,$value) = split(/=/,$_,2);
9384: $savedState{$key} = $value;
9385: }
9386: }
9387: return \%savedState;
9388: }
9389:
9390: #--- Href with symb and command ---
9391:
9392: sub href_symb_cmd {
9393: my ($symb,$cmd)=@_;
9394: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9395: }
9396:
9397: sub grading_menu {
9398: my ($request) = @_;
9399: my ($symb)=&get_symb($request);
9400: if (!$symb) {return '';}
9401: my $probTitle = &Apache::lonnet::gettitle($symb);
9402: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
9403:
9404: $request->print($table);
9405: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9406: 'handgrade'=>$hdgrade,
9407: 'probTitle'=>$probTitle,
9408: 'command'=>'submit_options',
9409: 'saveState'=>"",
9410: 'gradingMenu'=>1,
9411: 'showgrading'=>"yes");
9412:
9413: my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9414:
9415: $fields{'command'} = 'csvform';
9416: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9417:
9418: $fields{'command'} = 'processclicker';
9419: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9420:
9421: $fields{'command'} = 'scantron_selectphase';
9422: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9423:
9424: my @menu = ({ categorytitle=>'Course Grading',
9425: items =>[
9426: { linktext => 'Manual Grading/View Submissions',
9427: url => $url1,
9428: permission => 'F',
9429: icon => 'edit-find-replace.png',
9430: linktitle => 'Start the process of hand grading submissions.'
9431: },
9432: { linktext => 'Upload Scores',
9433: url => $url2,
9434: permission => 'F',
9435: icon => 'uploadscores.png',
9436: linktitle => 'Specify a file containing the class scores for current resource.'
9437: },
9438: { linktext => 'Process Clicker',
9439: url => $url3,
9440: permission => 'F',
9441: icon => 'addClickerInfoFile.png',
9442: linktitle => 'Specify a file containing the clicker information for this resource.'
9443: },
9444: { linktext => 'Grade/Manage/Review Bubblesheets',
9445: url => $url4,
9446: permission => 'F',
9447: icon => 'stat.png',
9448: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9449: }
9450: ]
9451: });
9452:
9453: #$fields{'command'} = 'verify';
9454: #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9455: #
9456: # Create the menu
9457: my $Str;
9458: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
9459: $Str .= '<form method="post" action="" name="gradingMenu">';
9460: $Str .= '<input type="hidden" name="command" value="" />'.
9461: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9462: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
9463: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
9464: '<input type="hidden" name="saveState" value="" />'."\n".
9465: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
9466: '<input type="hidden" name="showgrading" value="yes" />'."\n";
9467:
9468: $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
9469: #$menudata->{'jscript'}
9470: $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
9471: ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
9472: ' /> '.
9473: &Apache::lonnet::recprefix($env{'request.course.id'}).
9474: '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
9475:
9476: $Str .="</form>\n";
9477: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
9478: $request->print(<<GRADINGMENUJS);
9479: <script type="text/javascript" language="javascript">
9480: function checkChoice(formname,val,cmdx) {
9481: if (val <= 2) {
9482: var cmd = radioSelection(formname.radioChoice);
9483: var cmdsave = cmd;
9484: } else {
9485: cmd = cmdx;
9486: cmdsave = 'submission';
9487: }
9488: formname.command.value = cmd;
9489: if (val < 5) formname.submit();
9490: if (val == 5) {
9491: if (!checkReceiptNo(formname,'notOK')) {
9492: return false;
9493: } else {
9494: formname.submit();
9495: }
9496: }
9497: }
9498:
9499: function checkReceiptNo(formname,nospace) {
9500: var receiptNo = formname.receipt.value;
9501: var checkOpt = false;
9502: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
9503: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
9504: if (checkOpt) {
9505: alert("$receiptalert");
9506: formname.receipt.value = "";
9507: formname.receipt.focus();
9508: return false;
9509: }
9510: return true;
9511: }
9512: </script>
9513: GRADINGMENUJS
9514: &commonJSfunctions($request);
9515: return $Str;
9516: }
9517:
9518:
9519: #--- Displays the submissions first page -------
9520: sub submit_options {
9521: my ($request) = @_;
9522: my ($symb)=&get_symb($request);
9523: if (!$symb) {return '';}
9524: my $probTitle = &Apache::lonnet::gettitle($symb);
9525:
9526: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
9527: $request->print(<<GRADINGMENUJS);
9528: <script type="text/javascript" language="javascript">
9529: function checkChoice(formname,val,cmdx) {
9530: if (val <= 2) {
9531: var cmd = radioSelection(formname.radioChoice);
9532: var cmdsave = cmd;
9533: } else {
9534: cmd = cmdx;
9535: cmdsave = 'submission';
9536: }
9537: formname.command.value = cmd;
9538: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
9539: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
9540: if (val < 5) formname.submit();
9541: if (val == 5) {
9542: if (!checkReceiptNo(formname,'notOK')) { return false;}
9543: formname.submit();
9544: }
9545: if (val < 7) formname.submit();
9546: }
9547:
9548: function checkReceiptNo(formname,nospace) {
9549: var receiptNo = formname.receipt.value;
9550: var checkOpt = false;
9551: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
9552: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
9553: if (checkOpt) {
9554: alert("$receiptalert");
9555: formname.receipt.value = "";
9556: formname.receipt.focus();
9557: return false;
9558: }
9559: return true;
9560: }
9561: </script>
9562: GRADINGMENUJS
9563: &commonJSfunctions($request);
9564: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
9565: my $result;
9566: my (undef,$sections) = &getclasslist('all','0');
9567: my $savedState = &savedState();
9568: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
9569: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
9570: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
9571: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
9572:
9573: # Preselect sections
9574: my $selsec="";
9575: if (ref($sections)) {
9576: foreach my $section (sort(@$sections)) {
9577: $selsec.='<option value="'.$section.'" '.
9578: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
9579: }
9580: }
9581:
9582: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9583: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9584: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
9585: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
9586: '<input type="hidden" name="command" value="" />'."\n".
9587: '<input type="hidden" name="saveState" value="" />'."\n".
9588: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
9589: '<input type="hidden" name="showgrading" value="yes" />'."\n";
9590:
9591: $result.='
9592: <h2>
9593: '.&mt('Grade Current Resource').'
9594: </h2>
9595: <div>
9596: '.$table.'
9597: </div>
9598:
9599: <div class="LC_columnSection">
9600:
9601: <fieldset>
9602: <legend>
9603: '.&mt('Sections').'
9604: </legend>
9605: <select name="section" multiple="multiple" size="5">'."\n";
9606: $result.= $selsec;
9607: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
9608: $result.='
9609: </fieldset>
9610:
9611: <fieldset>
9612: <legend>
9613: '.&mt('Groups').'
9614: </legend>
9615: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9616: </fieldset>
9617:
9618: <fieldset>
9619: <legend>
9620: '.&mt('Access Status').'
9621: </legend>
9622: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
9623: </fieldset>
9624:
9625: <fieldset>
9626: <legend>
9627: '.&mt('Submission Status').'
9628: </legend>
9629: <select name="submitonly" size="5">
9630: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
9631: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
9632: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
9633: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
9634: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
9635: </select>
9636: </fieldset>
9637:
9638: </div>
9639:
9640: <br />
9641: <div>
9642: <div>
9643: <label>
9644: <input type="radio" name="radioChoice" value="submission" '.
9645: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
9646: &mt('Select individual students to grade and view submissions.').'
9647: </label>
9648: </div>
9649: <div>
9650: <label>
9651: <input type="radio" name="radioChoice" value="viewgrades" '.
9652: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
9653: &mt('Grade all selected students in a grading table.').'
9654: </label>
9655: </div>
9656: <div>
9657: <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
9658: </div>
9659: </div>
9660:
9661:
9662: <h2>
9663: '.&mt('Grade Complete Folder for One Student').'
9664: </h2>
9665: <div>
9666: <div>
9667: <label>
9668: <input type="radio" name="radioChoice" value="pickStudentPage" '.
9669: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
9670: &mt('The <b>complete</b> page/sequence/folder: For one student').'
9671: </label>
9672: </div>
9673: <div>
9674: <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
9675: </div>
9676: </div>
9677: </form>';
9678: $result .= &show_grading_menu_form($symb);
9679: return $result;
9680: }
9681:
9682: sub reset_perm {
9683: undef(%perm);
9684: }
9685:
9686: sub init_perm {
9687: &reset_perm();
9688: foreach my $test_perm ('vgr','mgr','opa') {
9689:
9690: my $scope = $env{'request.course.id'};
9691: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9692:
9693: $scope .= '/'.$env{'request.course.sec'};
9694: if ( $perm{$test_perm}=
9695: &Apache::lonnet::allowed($test_perm,$scope)) {
9696: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9697: } else {
9698: delete($perm{$test_perm});
9699: }
9700: }
9701: }
9702: }
9703:
9704: sub init_old_essays {
9705: my ($symb,$apath,$adom,$aname) = @_;
9706: if ($symb ne '') {
9707: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9708: if (keys(%essays) > 0) {
9709: $old_essays{$symb} = \%essays;
9710: }
9711: }
9712: return;
9713: }
9714:
9715: sub reset_old_essays {
9716: undef(%old_essays);
9717: }
9718:
9719: sub gather_clicker_ids {
9720: my %clicker_ids;
9721:
9722: my $classlist = &Apache::loncoursedata::get_classlist();
9723:
9724: # Set up a couple variables.
9725: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9726: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9727: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9728:
9729: foreach my $student (keys(%$classlist)) {
9730: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9731: my $username = $classlist->{$student}->[$username_idx];
9732: my $domain = $classlist->{$student}->[$domain_idx];
9733: my $clickers =
9734: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9735: foreach my $id (split(/\,/,$clickers)) {
9736: $id=~s/^[\#0]+//;
9737: $id=~s/[\-\:]//g;
9738: if (exists($clicker_ids{$id})) {
9739: $clicker_ids{$id}.=','.$username.':'.$domain;
9740: } else {
9741: $clicker_ids{$id}=$username.':'.$domain;
9742: }
9743: }
9744: }
9745: return %clicker_ids;
9746: }
9747:
9748: sub gather_adv_clicker_ids {
9749: my %clicker_ids;
9750: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9751: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9752: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9753: foreach my $element (sort(keys(%coursepersonnel))) {
9754: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9755: my ($puname,$pudom)=split(/\:/,$person);
9756: my $clickers =
9757: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9758: foreach my $id (split(/\,/,$clickers)) {
9759: $id=~s/^[\#0]+//;
9760: $id=~s/[\-\:]//g;
9761: if (exists($clicker_ids{$id})) {
9762: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9763: } else {
9764: $clicker_ids{$id}=$puname.':'.$pudom;
9765: }
9766: }
9767: }
9768: }
9769: return %clicker_ids;
9770: }
9771:
9772: sub clicker_grading_parameters {
9773: return ('gradingmechanism' => 'scalar',
9774: 'upfiletype' => 'scalar',
9775: 'specificid' => 'scalar',
9776: 'pcorrect' => 'scalar',
9777: 'pincorrect' => 'scalar');
9778: }
9779:
9780: sub process_clicker {
9781: my ($r)=@_;
9782: my ($symb)=&get_symb($r);
9783: if (!$symb) {return '';}
9784: my $result=&checkforfile_js();
9785: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
9786: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
9787: $result.=$table;
9788: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
9789: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
9790: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource.').
9791: '</b></td></tr>'."\n";
9792: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
9793: # Attempt to restore parameters from last session, set defaults if not present
9794: my %Saveable_Parameters=&clicker_grading_parameters();
9795: &Apache::loncommon::restore_course_settings('grades_clicker',
9796: \%Saveable_Parameters);
9797: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9798: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9799: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9800: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9801:
9802: my %checked;
9803: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9804: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9805: $checked{$gradingmechanism}=' checked="checked"';
9806: }
9807: }
9808:
9809: my $upload=&mt("Upload File");
9810: my $type=&mt("Type");
9811: my $attendance=&mt("Award points just for participation");
9812: my $personnel=&mt("Correctness determined from response by course personnel");
9813: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9814: my $given=&mt("Correctness determined from given list of answers").' '.
9815: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9816: my $pcorrect=&mt("Percentage points for correct solution");
9817: my $pincorrect=&mt("Percentage points for incorrect solution");
9818: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9819: {'iclicker' => 'i>clicker',
9820: 'interwrite' => 'interwrite PRS',
9821: 'turning' => 'Turning Technologies'});
9822: $symb = &Apache::lonenc::check_encrypt($symb);
9823: $result.=<<ENDUPFORM;
9824: <script type="text/javascript">
9825: function sanitycheck() {
9826: // Accept only integer percentages
9827: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9828: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9829: // Find out grading choice
9830: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9831: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9832: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9833: }
9834: }
9835: // By default, new choice equals user selection
9836: newgradingchoice=gradingchoice;
9837: // Not good to give more points for false answers than correct ones
9838: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9839: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9840: }
9841: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9842: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9843: document.forms.gradesupload.pcorrect.value=100;
9844: document.forms.gradesupload.pincorrect.value=100;
9845: }
9846: // If the values are different, cannot be attendance only
9847: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9848: (gradingchoice=='attendance')) {
9849: newgradingchoice='personnel';
9850: }
9851: // Change grading choice to new one
9852: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9853: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9854: document.forms.gradesupload.gradingmechanism[i].checked=true;
9855: } else {
9856: document.forms.gradesupload.gradingmechanism[i].checked=false;
9857: }
9858: }
9859: // Remember the old state
9860: document.forms.gradesupload.waschecked.value=newgradingchoice;
9861: }
9862: </script>
9863: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
9864: <input type="hidden" name="symb" value="$symb" />
9865: <input type="hidden" name="command" value="processclickerfile" />
9866: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
9867: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
9868: <input type="file" name="upfile" size="50" />
9869: <br /><label>$type: $selectform</label>
9870: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
9871: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
9872: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
9873: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
9874: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
9875: <br />
9876: <input type="text" name="givenanswer" size="50" />
9877: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
9878: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
9879: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
9880: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
9881: </form>
9882: ENDUPFORM
9883: $result.='</td></tr></table>'."\n".
9884: '</td></tr></table><br /><br />'."\n";
9885: $result.=&show_grading_menu_form($symb);
9886: return $result;
9887: }
9888:
9889: sub process_clicker_file {
9890: my ($r)=@_;
9891: my ($symb)=&get_symb($r);
9892: if (!$symb) {return '';}
9893:
9894: my %Saveable_Parameters=&clicker_grading_parameters();
9895: &Apache::loncommon::store_course_settings('grades_clicker',
9896: \%Saveable_Parameters);
9897:
9898: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
9899: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
9900: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
9901: return $result.&show_grading_menu_form($symb);
9902: }
9903: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
9904: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
9905: return $result.&show_grading_menu_form($symb);
9906: }
9907: my $foundgiven=0;
9908: if ($env{'form.gradingmechanism'} eq 'given') {
9909: $env{'form.givenanswer'}=~s/^\s*//gs;
9910: $env{'form.givenanswer'}=~s/\s*$//gs;
9911: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
9912: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
9913: my @answers=split(/\,/,$env{'form.givenanswer'});
9914: $foundgiven=$#answers+1;
9915: }
9916: my %clicker_ids=&gather_clicker_ids();
9917: my %correct_ids;
9918: if ($env{'form.gradingmechanism'} eq 'personnel') {
9919: %correct_ids=&gather_adv_clicker_ids();
9920: }
9921: if ($env{'form.gradingmechanism'} eq 'specific') {
9922: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
9923: $correct_id=~tr/a-z/A-Z/;
9924: $correct_id=~s/\s//gs;
9925: $correct_id=~s/^[\#0]+//;
9926: $correct_id=~s/[\-\:]//g;
9927: if ($correct_id) {
9928: $correct_ids{$correct_id}='specified';
9929: }
9930: }
9931: }
9932: if ($env{'form.gradingmechanism'} eq 'attendance') {
9933: $result.=&mt('Score based on attendance only');
9934: } elsif ($env{'form.gradingmechanism'} eq 'given') {
9935: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
9936: } else {
9937: my $number=0;
9938: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
9939: foreach my $id (sort(keys(%correct_ids))) {
9940: $result.='<br /><tt>'.$id.'</tt> - ';
9941: if ($correct_ids{$id} eq 'specified') {
9942: $result.=&mt('specified');
9943: } else {
9944: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
9945: $result.=&Apache::loncommon::plainname($uname,$udom);
9946: }
9947: $number++;
9948: }
9949: $result.="</p>\n";
9950: if ($number==0) {
9951: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
9952: return $result.&show_grading_menu_form($symb);
9953: }
9954: }
9955: if (length($env{'form.upfile'}) < 2) {
9956: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
9957: '<span class="LC_error">',
9958: '</span>',
9959: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
9960: return $result.&show_grading_menu_form($symb);
9961: }
9962:
9963: # Were able to get all the info needed, now analyze the file
9964:
9965: $result.=&Apache::loncommon::studentbrowser_javascript();
9966: $symb = &Apache::lonenc::check_encrypt($symb);
9967: my $heading=&mt('Scanning clicker file');
9968: $result.=(<<ENDHEADER);
9969: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
9970: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
9971: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
9972: <form method="post" action="/adm/grades" name="clickeranalysis">
9973: <input type="hidden" name="symb" value="$symb" />
9974: <input type="hidden" name="command" value="assignclickergrades" />
9975: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
9976: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
9977: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
9978: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
9979: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9980: ENDHEADER
9981: if ($env{'form.gradingmechanism'} eq 'given') {
9982: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9983: }
9984: my %responses;
9985: my @questiontitles;
9986: my $errormsg='';
9987: my $number=0;
9988: if ($env{'form.upfiletype'} eq 'iclicker') {
9989: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9990: }
9991: if ($env{'form.upfiletype'} eq 'interwrite') {
9992: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9993: }
9994: if ($env{'form.upfiletype'} eq 'turning') {
9995: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
9996: }
9997: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9998: '<input type="hidden" name="number" value="'.$number.'" />'.
9999: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10000: $env{'form.pcorrect'},$env{'form.pincorrect'}).
10001: '<br />';
10002: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10003: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10004: return $result.&show_grading_menu_form($symb);
10005: }
10006: # Remember Question Titles
10007: # FIXME: Possibly need delimiter other than ":"
10008: for (my $i=0;$i<$number;$i++) {
10009: $result.='<input type="hidden" name="question:'.$i.'" value="'.
10010: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10011: }
10012: my $correct_count=0;
10013: my $student_count=0;
10014: my $unknown_count=0;
10015: # Match answers with usernames
10016: # FIXME: Possibly need delimiter other than ":"
10017: foreach my $id (keys(%responses)) {
10018: if ($correct_ids{$id}) {
10019: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10020: $correct_count++;
10021: } elsif ($clicker_ids{$id}) {
10022: if ($clicker_ids{$id}=~/\,/) {
10023: # More than one user with the same clicker!
10024: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10025: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10026: "<select name='multi".$id."'>";
10027: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10028: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10029: }
10030: $result.='</select>';
10031: $unknown_count++;
10032: } else {
10033: # Good: found one and only one user with the right clicker
10034: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10035: $student_count++;
10036: }
10037: } else {
10038: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10039: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10040: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
10041: "\n".&mt("Domain").": ".
10042: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
10043: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10044: $unknown_count++;
10045: }
10046: }
10047: $result.='<hr />'.
10048: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10049: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10050: if ($correct_count==0) {
10051: $errormsg.="Found no correct answers for grading!";
10052: } elsif ($correct_count>1) {
10053: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10054: }
10055: }
10056: if ($number<1) {
10057: $errormsg.="Found no questions.";
10058: }
10059: if ($errormsg) {
10060: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10061: } else {
10062: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10063: }
10064: $result.='</form></td></tr></table>'."\n".
10065: '</td></tr></table><br /><br />'."\n";
10066: return $result.&show_grading_menu_form($symb);
10067: }
10068:
10069: sub iclicker_eval {
10070: my ($questiontitles,$responses)=@_;
10071: my $number=0;
10072: my $errormsg='';
10073: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10074: my %components=&Apache::loncommon::record_sep($line);
10075: my @entries=map {$components{$_}} (sort(keys(%components)));
10076: if ($entries[0] eq 'Question') {
10077: for (my $i=3;$i<$#entries;$i+=6) {
10078: $$questiontitles[$number]=$entries[$i];
10079: $number++;
10080: }
10081: }
10082: if ($entries[0]=~/^\#/) {
10083: my $id=$entries[0];
10084: my @idresponses;
10085: $id=~s/^[\#0]+//;
10086: for (my $i=0;$i<$number;$i++) {
10087: my $idx=3+$i*6;
10088: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10089: push(@idresponses,$entries[$idx]);
10090: }
10091: $$responses{$id}=join(',',@idresponses);
10092: }
10093: }
10094: return ($errormsg,$number);
10095: }
10096:
10097: sub interwrite_eval {
10098: my ($questiontitles,$responses)=@_;
10099: my $number=0;
10100: my $errormsg='';
10101: my $skipline=1;
10102: my $questionnumber=0;
10103: my %idresponses=();
10104: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10105: my %components=&Apache::loncommon::record_sep($line);
10106: my @entries=map {$components{$_}} (sort(keys(%components)));
10107: if ($entries[1] eq 'Time') { $skipline=0; next; }
10108: if ($entries[1] eq 'Response') { $skipline=1; }
10109: next if $skipline;
10110: if ($entries[0]!=$questionnumber) {
10111: $questionnumber=$entries[0];
10112: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10113: $number++;
10114: }
10115: my $id=$entries[4];
10116: $id=~s/^[\#0]+//;
10117: $id=~s/^v\d*\://i;
10118: $id=~s/[\-\:]//g;
10119: $idresponses{$id}[$number]=$entries[6];
10120: }
10121: foreach my $id (keys(%idresponses)) {
10122: $$responses{$id}=join(',',@{$idresponses{$id}});
10123: $$responses{$id}=~s/^\s*\,//;
10124: }
10125: return ($errormsg,$number);
10126: }
10127:
10128: sub turning_eval {
10129: my ($questiontitles,$responses)=@_;
10130: my $number=0;
10131: my $errormsg='';
10132: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10133: my %components=&Apache::loncommon::record_sep($line);
10134: my @entries=map {$components{$_}} (sort(keys(%components)));
10135: if ($#entries>$number) { $number=$#entries; }
10136: my $id=$entries[0];
10137: my @idresponses;
10138: $id=~s/^[\#0]+//;
10139: unless ($id) { next; }
10140: for (my $idx=1;$idx<=$#entries;$idx++) {
10141: $entries[$idx]=~s/\,/\;/g;
10142: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10143: push(@idresponses,$entries[$idx]);
10144: }
10145: $$responses{$id}=join(',',@idresponses);
10146: }
10147: for (my $i=1; $i<=$number; $i++) {
10148: $$questiontitles[$i]=&mt('Question [_1]',$i);
10149: }
10150: return ($errormsg,$number);
10151: }
10152:
10153: sub assign_clicker_grades {
10154: my ($r)=@_;
10155: my ($symb)=&get_symb($r);
10156: if (!$symb) {return '';}
10157: # See which part we are saving to
10158: my $res_error;
10159: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10160: if ($res_error) {
10161: return &navmap_errormsg();
10162: }
10163: # FIXME: This should probably look for the first handgradeable part
10164: my $part=$$partlist[0];
10165: # Start screen output
10166: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10167:
10168: $result .= '<br />'.
10169: &Apache::loncommon::start_data_table().
10170: &Apache::loncommon::start_data_table_header_row().
10171: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10172: &Apache::loncommon::end_data_table_header_row().
10173: &Apache::loncommon::start_data_table_row().'<td>';
10174:
10175: # Get correct result
10176: # FIXME: Possibly need delimiter other than ":"
10177: my @correct=();
10178: my $gradingmechanism=$env{'form.gradingmechanism'};
10179: my $number=$env{'form.number'};
10180: if ($gradingmechanism ne 'attendance') {
10181: foreach my $key (keys(%env)) {
10182: if ($key=~/^form\.correct\:/) {
10183: my @input=split(/\,/,$env{$key});
10184: for (my $i=0;$i<=$#input;$i++) {
10185: if (($correct[$i]) && ($input[$i]) &&
10186: ($correct[$i] ne $input[$i])) {
10187: $result.='<br /><span class="LC_warning">'.
10188: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10189: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10190: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10191: $correct[$i]=$input[$i];
10192: }
10193: }
10194: }
10195: }
10196: for (my $i=0;$i<$number;$i++) {
10197: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10198: $result.='<br /><span class="LC_error">'.
10199: &mt('No correct result given for question "[_1]"!',
10200: $env{'form.question:'.$i}).'</span>';
10201: }
10202: }
10203: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10204: }
10205: # Start grading
10206: my $pcorrect=$env{'form.pcorrect'};
10207: my $pincorrect=$env{'form.pincorrect'};
10208: my $storecount=0;
10209: my %users=();
10210: foreach my $key (keys(%env)) {
10211: my $user='';
10212: if ($key=~/^form\.student\:(.*)$/) {
10213: $user=$1;
10214: }
10215: if ($key=~/^form\.unknown\:(.*)$/) {
10216: my $id=$1;
10217: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10218: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10219: } elsif ($env{'form.multi'.$id}) {
10220: $user=$env{'form.multi'.$id};
10221: }
10222: }
10223: if ($user) {
10224: if ($users{$user}) {
10225: $result.='<br /><span class="LC_warning">'.
10226: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10227: '</span><br />';
10228: }
10229: $users{$user}=1;
10230: my @answer=split(/\,/,$env{$key});
10231: my $sum=0;
10232: my $realnumber=$number;
10233: for (my $i=0;$i<$number;$i++) {
10234: if ($correct[$i] eq '-') {
10235: $realnumber--;
10236: } elsif ($answer[$i]) {
10237: if ($gradingmechanism eq 'attendance') {
10238: $sum+=$pcorrect;
10239: } elsif ($correct[$i] eq '*') {
10240: $sum+=$pcorrect;
10241: } else {
10242: # We actually grade if correct or not
10243: my $increment=$pincorrect;
10244: # Special case: numerical answer "0"
10245: if ($correct[$i] eq '0') {
10246: if ($answer[$i]=~/^[0\.]+$/) {
10247: $increment=$pcorrect;
10248: }
10249: # General numerical answer, both evaluate to something non-zero
10250: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10251: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10252: $increment=$pcorrect;
10253: }
10254: # Must be just alphanumeric
10255: } elsif ($answer[$i] eq $correct[$i]) {
10256: $increment=$pcorrect;
10257: }
10258: $sum+=$increment;
10259: }
10260: }
10261: }
10262: my $ave=$sum/(100*$realnumber);
10263: # Store
10264: my ($username,$domain)=split(/\:/,$user);
10265: my %grades=();
10266: $grades{"resource.$part.solved"}='correct_by_override';
10267: $grades{"resource.$part.awarded"}=$ave;
10268: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10269: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10270: $env{'request.course.id'},
10271: $domain,$username);
10272: if ($returncode ne 'ok') {
10273: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10274: } else {
10275: $storecount++;
10276: }
10277: }
10278: }
10279: # We are done
10280: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10281: '</td>'.
10282: &Apache::loncommon::end_data_table_row().
10283: &Apache::loncommon::end_data_table()."<br /><br />\n";
10284: return $result.&show_grading_menu_form($symb);
10285: }
10286:
10287: sub navmap_errormsg {
10288: return '<div class="LC_error">'.
10289: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10290: &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>').
10291: '</div>';
10292: }
10293:
10294: sub startpage {
10295: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10296: if ($nomenu) {
10297: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10298: } else {
10299: $r->print(&Apache::loncommon::start_page('Grading',$js,
10300: {'bread_crumbs' => $crumbs}));
10301: }
10302: unless ($nodisplayflag) {
10303: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10304: }
10305: }
10306:
10307: sub handler {
10308: my $request=$_[0];
10309: &reset_caches();
10310: if ($request->header_only) {
10311: &Apache::loncommon::content_type($request,'text/html');
10312: $request->send_http_header;
10313: return OK;
10314: }
10315: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10316:
10317: my $symb=&get_symb($request,1);
10318: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10319: my $command=$commands[0];
10320:
10321: if ($#commands > 0) {
10322: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10323: }
10324:
10325: $ssi_error = 0;
10326: my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10327: my $start_page = &Apache::loncommon::start_page('Grading',undef,
10328: {'bread_crumbs' => $brcrum});
10329: if ($symb eq '' && $command eq '') {
10330: if ($env{'user.adv'}) {
10331: &Apache::loncommon::content_type($request,'text/html');
10332: $request->send_http_header;
10333: $request->print($start_page);
10334: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10335: ($env{'form.codethree'})) {
10336: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10337: $env{'form.codethree'};
10338: my ($tsymb,$tuname,$tudom,$tcrsid)=
10339: &Apache::lonnet::checkin($token);
10340: if ($tsymb) {
10341: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10342: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10343: $request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10344: ('grade_username' => $tuname,
10345: 'grade_domain' => $tudom,
10346: 'grade_courseid' => $tcrsid,
10347: 'grade_symb' => $tsymb)));
10348: } else {
10349: $request->print('<h3>Not authorized: '.$token.'</h3>');
10350: }
10351: } else {
10352: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10353: }
10354: } else {
10355: $request->print(&Apache::lonxml::tokeninputfield());
10356: }
10357: } elsif ($env{'request.course.id'}) {
10358: &init_perm();
10359: if (!%perm) {
10360: $request->internal_redirect('/adm/quickgrades');
10361: return OK;
10362: } else {
10363: &Apache::loncommon::content_type($request,'text/html');
10364: $request->send_http_header;
10365: $request->print($start_page);
10366: }
10367: }
10368: } else {
10369: &init_perm();
10370: if (!$env{'request.course.id'}) {
10371: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10372: ($command =~ /^scantronupload/)) {
10373: # Not in a course.
10374: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10375: return HTTP_NOT_ACCEPTABLE;
10376: }
10377: } elsif (!%perm) {
10378: $request->internal_redirect('/adm/quickgrades');
10379: }
10380: &Apache::loncommon::content_type($request,'text/html');
10381: $request->send_http_header;
10382: unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10383: $request->print($start_page);
10384: }
10385: if ($command eq 'submission' && $perm{'vgr'}) {
10386: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10387: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10388: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10389: &choose_task_version_form($symb,$env{'form.student'},
10390: $env{'form.userdom'});
10391: }
10392: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10393: if ($versionform) {
10394: $request->print($versionform);
10395: }
10396: $request->print('<br clear="all" />');
10397: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10398: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10399: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10400: &choose_task_version_form($symb,$env{'form.student'},
10401: $env{'form.userdom'},
10402: $env{'form.inhibitmenu'});
10403: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10404: if ($versionform) {
10405: $request->print($versionform);
10406: }
10407: $request->print('<br clear="all" />');
10408: $request->print(&show_previous_task_version($request,$symb));
10409: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10410: &pickStudentPage($request);
10411: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10412: &displayPage($request);
10413: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10414: &updateGradeByPage($request);
10415: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10416: &processGroup($request);
10417: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10418: $request->print(&grading_menu($request));
10419: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10420: $request->print(&submit_options($request));
10421: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10422: $request->print(&viewgrades($request));
10423: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10424: $request->print(&processHandGrade($request));
10425: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10426: $request->print(&editgrades($request));
10427: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10428: $request->print(&verifyreceipt($request));
10429: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10430: $request->print(&process_clicker($request));
10431: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10432: $request->print(&process_clicker_file($request));
10433: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10434: $request->print(&assign_clicker_grades($request));
10435: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10436: $request->print(&upcsvScores_form($request));
10437: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10438: $request->print(&csvupload($request));
10439: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10440: $request->print(&csvuploadmap($request));
10441: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10442: if ($env{'form.associate'} ne 'Reverse Association') {
10443: $request->print(&csvuploadoptions($request));
10444: } else {
10445: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10446: $env{'form.upfile_associate'} = 'reverse';
10447: } else {
10448: $env{'form.upfile_associate'} = 'forward';
10449: }
10450: $request->print(&csvuploadmap($request));
10451: }
10452: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10453: $request->print(&csvuploadassign($request));
10454: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10455: $request->print(&scantron_selectphase($request));
10456: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10457: $request->print(&scantron_do_warning($request));
10458: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10459: $request->print(&scantron_validate_file($request));
10460: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10461: $request->print(&scantron_process_students($request));
10462: } elsif ($command eq 'scantronupload' &&
10463: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10464: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10465: $request->print(&scantron_upload_scantron_data($request));
10466: } elsif ($command eq 'scantronupload_save' &&
10467: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10468: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10469: $request->print(&scantron_upload_scantron_data_save($request));
10470: } elsif ($command eq 'scantron_download' &&
10471: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10472: $request->print(&scantron_download_scantron_data($request));
10473: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10474: $request->print(&checkscantron_results($request));
10475: } elsif ($command) {
10476: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10477: }
10478: }
10479: if ($ssi_error) {
10480: &ssi_print_error($request);
10481: }
10482: $request->print(&Apache::loncommon::end_page());
10483: &reset_caches();
10484: return OK;
10485: }
10486:
10487: 1;
10488:
10489: __END__;
10490:
10491:
10492: =head1 NAME
10493:
10494: Apache::grades
10495:
10496: =head1 SYNOPSIS
10497:
10498: Handles the viewing of grades.
10499:
10500: This is part of the LearningOnline Network with CAPA project
10501: described at http://www.lon-capa.org.
10502:
10503: =head1 OVERVIEW
10504:
10505: Do an ssi with retries:
10506: While I'd love to factor out this with the vesrion in lonprintout,
10507: 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
10508: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10509:
10510: At least the logic that drives this has been pulled out into loncommon.
10511:
10512:
10513:
10514: ssi_with_retries - Does the server side include of a resource.
10515: if the ssi call returns an error we'll retry it up to
10516: the number of times requested by the caller.
10517: If we still have a proble, no text is appended to the
10518: output and we set some global variables.
10519: to indicate to the caller an SSI error occurred.
10520: All of this is supposed to deal with the issues described
10521: in LonCAPA BZ 5631 see:
10522: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10523: by informing the user that this happened.
10524:
10525: Parameters:
10526: resource - The resource to include. This is passed directly, without
10527: interpretation to lonnet::ssi.
10528: form - The form hash parameters that guide the interpretation of the resource
10529:
10530: retries - Number of retries allowed before giving up completely.
10531: Returns:
10532: On success, returns the rendered resource identified by the resource parameter.
10533: Side Effects:
10534: The following global variables can be set:
10535: ssi_error - If an unrecoverable error occurred this becomes true.
10536: It is up to the caller to initialize this to false
10537: if desired.
10538: ssi_error_resource - If an unrecoverable error occurred, this is the value
10539: of the resource that could not be rendered by the ssi
10540: call.
10541: ssi_error_message - The error string fetched from the ssi response
10542: in the event of an error.
10543:
10544:
10545: =head1 HANDLER SUBROUTINE
10546:
10547: ssi_with_retries()
10548:
10549: =head1 SUBROUTINES
10550:
10551: =over
10552:
10553: =item scantron_get_correction() :
10554:
10555: Builds the interface screen to interact with the operator to fix a
10556: specific error condition in a specific scanline
10557:
10558: Arguments:
10559: $r - Apache request object
10560: $i - number of the current scanline
10561: $scan_record - hash ref as returned from &scantron_parse_scanline()
10562: $scan_config - hash ref as returned from &get_scantron_config()
10563: $line - full contents of the current scanline
10564: $error - error condition, valid values are
10565: 'incorrectCODE', 'duplicateCODE',
10566: 'doublebubble', 'missingbubble',
10567: 'duplicateID', 'incorrectID'
10568: $arg - extra information needed
10569: For errors:
10570: - duplicateID - paper number that this studentID was seen before on
10571: - duplicateCODE - array ref of the paper numbers this CODE was
10572: seen on before
10573: - incorrectCODE - current incorrect CODE
10574: - doublebubble - array ref of the bubble lines that have double
10575: bubble errors
10576: - missingbubble - array ref of the bubble lines that have missing
10577: bubble errors
10578:
10579: $randomorder - True if exam folder has randomorder set
10580: $randompick - True if exam folder has randompick set
10581: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10582: for current line to question number used for same question
10583: in "Master Seqence" (as seen by Course Coordinator).
10584: $startline - Reference to hash where key is question number (0 is first)
10585: and value is number of first bubble line for current student
10586: or code-based randompick and/or randomorder.
10587:
10588:
10589: =item scantron_get_maxbubble() :
10590:
10591: Arguments:
10592: $nav_error - Reference to scalar which is a flag to indicate a
10593: failure to retrieve a navmap object.
10594: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10595: calling routine should trap the error condition and display the warning
10596: found in &navmap_errormsg().
10597:
10598: $scantron_config - Reference to bubblesheet format configuration hash.
10599:
10600: Returns the maximum number of bubble lines that are expected to
10601: occur. Does this by walking the selected sequence rendering the
10602: resource and then checking &Apache::lonxml::get_problem_counter()
10603: for what the current value of the problem counter is.
10604:
10605: Caches the results to $env{'form.scantron_maxbubble'},
10606: $env{'form.scantron.bubble_lines.n'},
10607: $env{'form.scantron.first_bubble_line.n'} and
10608: $env{"form.scantron.sub_bubblelines.n"}
10609: which are the total number of bubble lines, the number of bubble
10610: lines for response n and number of the first bubble line for response n,
10611: and a comma separated list of numbers of bubble lines for sub-questions
10612: (for optionresponse, matchresponse, and rankresponse items), for response n.
10613:
10614:
10615: =item scantron_validate_missingbubbles() :
10616:
10617: Validates all scanlines in the selected file to not have any
10618: answers that don't have bubbles that have not been verified
10619: to be bubble free.
10620:
10621: =item scantron_process_students() :
10622:
10623: Routine that does the actual grading of the bubblesheet information.
10624:
10625: The parsed scanline hash is added to %env
10626:
10627: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10628: foreach resource , with the form data of
10629:
10630: 'submitted' =>'scantron'
10631: 'grade_target' =>'grade',
10632: 'grade_username'=> username of student
10633: 'grade_domain' => domain of student
10634: 'grade_courseid'=> of course
10635: 'grade_symb' => symb of resource to grade
10636:
10637: This triggers a grading pass. The problem grading code takes care
10638: of converting the bubbled letter information (now in %env) into a
10639: valid submission.
10640:
10641: =item scantron_upload_scantron_data() :
10642:
10643: Creates the screen for adding a new bubblesheet data file to a course.
10644:
10645: =item scantron_upload_scantron_data_save() :
10646:
10647: Adds a provided bubble information data file to the course if user
10648: has the correct privileges to do so.
10649:
10650: =item valid_file() :
10651:
10652: Validates that the requested bubble data file exists in the course.
10653:
10654: =item scantron_download_scantron_data() :
10655:
10656: Shows a list of the three internal files (original, corrected,
10657: skipped) for a specific bubblesheet data file that exists in the
10658: course.
10659:
10660: =item scantron_validate_ID() :
10661:
10662: Validates all scanlines in the selected file to not have any
10663: invalid or underspecified student/employee IDs
10664:
10665: =item navmap_errormsg() :
10666:
10667: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10668: Should be called whenever the request to instantiate a navmap object fails.
10669:
10670: =back
10671:
10672: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>