1: # The LearningOnline Network with CAPA
2: #
3: # $Id: lonstudentsubmissions.pm,v 1.54.10.2 2010/09/12 17:37:24 raeburn Exp $
4: #
5: # Copyright Michigan State University Board of Trustees
6: #
7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
8: #
9: # LON-CAPA is free software; you can redistribute it and/or modify
10: # it under the terms of the GNU General Public License as published by
11: # the Free Software Foundation; either version 2 of the License, or
12: # (at your option) any later version.
13: #
14: # LON-CAPA is distributed in the hope that it will be useful,
15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17: # GNU General Public License for more details.
18: #
19: # You should have received a copy of the GNU General Public License
20: # along with LON-CAPA; if not, write to the Free Software
21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22: #
23: # /home/httpd/html/adm/gpl.txt
24: #
25: # http://www.lon-capa.org/
26: #
27: package Apache::lonstudentsubmissions;
28:
29: use strict;
30: use Apache::lonnet;
31: use Apache::loncommon();
32: use Apache::lonhtmlcommon();
33: use Apache::loncoursedata();
34: use Apache::lonstatistics;
35: use Apache::lonlocal;
36: use Apache::lonstathelpers;
37: use HTML::Entities();
38: use Time::Local();
39: use Spreadsheet::WriteExcel();
40: use Crypt::PasswdMD5;
41: use lib '/home/httpd/lib/perl/';
42: use LONCAPA;
43:
44:
45: my @SubmitButtons = ({ name => 'SelectAnother',
46: text => 'Choose a different Problem' },
47: { name => 'Generate',
48: text => 'Generate Report'},
49: );
50:
51: sub BuildStudentSubmissionsPage {
52: my ($r,$c)=@_;
53: #
54: my %Saveable_Parameters = ('Status' => 'scalar',
55: 'Section' => 'array',
56: 'NumPlots' => 'scalar',
57: );
58: &Apache::loncommon::store_course_settings('student_submissions',
59: \%Saveable_Parameters);
60: &Apache::loncommon::restore_course_settings('student_submissions',
61: \%Saveable_Parameters);
62: #
63: &Apache::lonstatistics::PrepareClasslist();
64: #
65: $r->print(&CreateInterface());
66: #
67: my @Students = @Apache::lonstatistics::Students;
68: #
69: if (@Students < 1) {
70: $r->print('<div class="LC_warning">'
71: .&mt('There are no students in the sections selected.')
72: .'</div>');
73: }
74: #
75: my @CacheButtonHTML =
76: &Apache::lonstathelpers::manage_caches($r,'Statistics','stats_status',
77: '<div class="LC_info">'.&mt('Loading student data...').'</div>');
78: $r->rflush();
79: #
80: if (exists($env{'form.problemchoice'}) &&
81: ! exists($env{'form.SelectAnother'})) {
82: foreach my $button (@SubmitButtons) {
83: if ($button->{'name'} eq 'break') {
84: $r->print("<br />\n");
85: } else {
86: $r->print('<input type="submit" name="'.$button->{'name'}.'" '.
87: 'value="'.&mt($button->{'text'}).'" />');
88: $r->print(' 'x5);
89: }
90: }
91: foreach my $html (@CacheButtonHTML) {
92: $r->print($html.(' 'x5));
93: }
94: #
95: $r->print('<hr />'.$/);
96: $r->rflush();
97: #
98: # Determine which problems we are to analyze
99: my @Symbs =
100: &Apache::lonstathelpers::get_selected_symbs('problemchoice');
101: foreach my $selected (@Symbs) {
102: $r->print('<input type="hidden" name="problemchoice" value="'.
103: $selected.'" />'.$/);
104: }
105: #
106: # Get resource objects
107: my $navmap = Apache::lonnavmaps::navmap->new();
108: if (!defined($navmap)) {
109: $r->print('<div class="LC_error">'.&mt("Internal error").'</div>');
110: return;
111: }
112: my %already_seen;
113: my (@Problems,$show_named);
114: unless (&Apache::loncommon::needs_gci_custom()) {
115: $show_named = 1;
116: }
117: foreach my $symb (@Symbs) {
118: my $resource = $navmap->getBySymb($symb);
119: push(@Problems,$resource);
120: }
121: # If these are to be anonymized, do a random shuffle of @Students.
122: unless ($show_named) {
123: &array_shuffle(\@Students);
124: }
125: my $threshold = $env{'course.'.$env{'request.course.id'}.'.internal.anonsurvey_threshold'};
126: if ($threshold eq '') {
127: my %domconfig =
128: &Apache::lonnet::get_dom('configuration',['coursedefaults'],
129: $env{'course.'.$env{'request.course.id'}.'.domain'});
130: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
131: $threshold = $domconfig{'coursedefaults'}{'anonsurvey_threshold'};
132: if ($threshold eq '') {
133: $threshold = 10;
134: }
135: } else {
136: $threshold = 10;
137: }
138: }
139: #
140: $r->print('<h4>'.
141: &Apache::lonstatistics::section_and_enrollment_description().
142: '</h4>');
143: if (! scalar(@Problems) || ! defined($Problems[0])) {
144: $r->print('resource is undefined');
145: } elsif (!$show_named && @Students < $threshold) {
146: $r->print(&mt('The number of students matching the selection criteria is too few for display of submission data for anonymous surveys.').'<br />'.&mt('There must be at least [quant,_1,student].',$threshold).' '.&mt('Contact a Domain Coordinator if you need the threshold to be changed for this course.'));
147: } else {
148: if (scalar(@Problems) == 1) {
149: my $resource = $Problems[0];
150: $r->print('<h1>'.$resource->title.'</h1>');
151: $r->print('<h3>'.$resource->src.'</h3>');
152: if ($env{'form.renderprob'} eq 'true') {
153: $r->print(&Apache::lonstathelpers::render_resource($resource));
154: $r->rflush();
155: }
156: }
157: if ($env{'form.output'} eq 'excel') {
158: &prepare_excel_output($r,\@Problems,\@Students,$show_named);
159: } elsif ($env{'form.output'} eq 'csv') {
160: &prepare_csv_output($r,\@Problems,\@Students,$show_named);
161: } else {
162: &prepare_html_output($r,\@Problems,\@Students,$show_named);
163: }
164: }
165: $r->print('<hr />');
166: } else {
167: $r->print('<input type="submit" name="Generate" value="'.
168: &mt('Prepare Report').'" />');
169: $r->print(' 'x5);
170: $r->print('<p>'.
171: &mt('Computing correct answers greatly increasese the amount of time required to prepare a report.').
172: '</p>');
173: $r->print('<p>'.
174: &mt('Please select problems and use the [_1]Prepare Report[_2] button to continue.','<b>','</b>').
175: '</p>');
176: $r->print(&Apache::lonstathelpers::MultipleProblemSelector
177: (undef,'problemchoice','Statistics'));
178: }
179: }
180:
181: sub array_shuffle {
182: my $array = shift;
183: return unless (ref($array) eq 'ARRAY');
184: my $i = scalar(@$array);
185: my $j;
186: foreach my $item (@$array) {
187: --$i;
188: $j = int(rand($i+1));
189: next if($i == $j);
190: @$array [$i,$j] = @$array[$j,$i];
191: }
192: return @$array;
193: }
194:
195: ##
196: ## get_extra_response_headers
197: ##
198:
199: sub get_extra_response_headers {
200: my ($show_named) = @_;
201: my @extra_resp_headers;
202: if ($env{'form.correctans'} eq 'true') {
203: push(@extra_resp_headers,'Correct');
204: }
205: if ($show_named) {
206: if ($env{'form.prob_status'} eq 'true') {
207: push(@extra_resp_headers,'Award Detail');
208: push(@extra_resp_headers,'Time');
209: push(@extra_resp_headers,'Attempt');
210: push(@extra_resp_headers,'Awarded');
211: }
212: }
213: return @extra_resp_headers;
214: }
215:
216: ##
217: ## get_headers:
218: ## return the proper headers for the given response
219: sub get_headers {
220: my ($prob,$partid,$respid,$resptype,$analysis,$output,$purpose,
221: @basic_headers) = @_;
222: my @headers;
223: if ($resptype eq 'essay' && $purpose eq 'display' &&
224: ($output eq 'html')) {# || scalar(@{$prob->parts})!=1)) {
225: @headers = ();
226: } elsif ($resptype =~ /^(option|match|rank)$/) {
227: my $prefix = '_';
228: if ($purpose eq 'display') {
229: $prefix = '';
230: }
231: my @foils =
232: map {
233: $prefix.$_;
234: } sort(keys(%{$analysis->{$partid.'.'.$respid}->{'_Foils'}}));
235: if (scalar(@basic_headers) && $basic_headers[0] eq 'Correct') {
236: @foils = map { ($_ , $_.' Correct') } @foils;
237: shift(@basic_headers); # Get rid of 'Correct'
238: }
239: @headers = (@foils,@basic_headers);
240: } elsif (lc($resptype) eq 'task') {
241: @headers = ('Grader','Status',@basic_headers,'Submission');
242: } else {
243: @headers = ('Submission',@basic_headers);
244: }
245: return @headers;
246: }
247:
248: #########################################################
249: #########################################################
250: ##
251: ## HTML Output Routines
252: ##
253: #########################################################
254: #########################################################
255: sub prepare_html_output {
256: my ($r,$problems,$students,$show_named) = @_;
257: my $c = $r->connection();
258: my $salt = '$1$'.$Apache::lonnet::perlvar{'AnonymousSalt'};
259: #
260: # Set a flag for the case when there is just one problem
261: my $single_response = 0;
262: if (scalar(@$problems) == 1 &&
263: $problems->[0]->countResponses == 1) {
264: $single_response = 1;
265: }
266: #
267: # Compute the number of columns per response
268: my @extra_resp_headers = &get_extra_response_headers($show_named);
269: #
270: # Create the table header
271: my @student_columns;
272: if ($show_named) {
273: @student_columns = @Apache::lonstatistics::SelectedStudentData;
274: if (grep(/^all$/,@student_columns)) {
275: @student_columns = qw(fullname username domain id section status groups comments);
276: }
277: } else {
278: @student_columns = ('username');
279: }
280: #
281: my %headers;
282: my $student_column_count = scalar(@student_columns);
283: $headers{'problem'} = qq{<th colspan="$student_column_count">\ </th>};
284: foreach (@student_columns) {
285: $headers{'student'}.= '<th>'.ucfirst($_).'</th>';
286: }
287: #
288: # we put the headers into the %headers hash
289: my $total_col = scalar(@student_columns);
290: my $nonempty_part_headers = 0;
291: #
292: my %problem_analysis;
293: foreach my $prob (@$problems) {
294: my %analysis = &Apache::lonstathelpers::get_problem_data($prob->src);
295: $problem_analysis{$prob->src}=\%analysis;
296: #
297: my $prob_span = 0;
298: my $single_part = 0;
299: if (scalar(@{$prob->parts}) == 1) {
300: $single_part = 1;
301: }
302: foreach my $partid (@{$prob->parts}) {
303: my $part_span = 0;
304: my $responses = [$prob->responseIds($partid)];
305: my $resptypes = [$prob->responseType($partid)];
306: for (my $i=0;$i<scalar(@$responses);$i++) {
307: my $respid = $responses->[$i];
308: my @headers = &get_headers($prob,$partid,$respid,
309: $resptypes->[$i],
310: $problem_analysis{$prob->src},
311: 'html','display',
312: @extra_resp_headers);
313: if (scalar(@headers)>0) {
314: $total_col += scalar(@headers);
315: $part_span += scalar(@headers);
316: $headers{'response'} .=
317: '<th colspan="'.scalar(@headers).'">'.
318: &mt('Response [_1]',$responses->[$i]).'</th>';
319: $headers{'student'}.= '<th><span class="LC_nobreak">'.
320: join('</span></th><th><span class="LC_nobreak">',
321: @headers).
322: '</span></th>';
323: }
324: }
325: if ($part_span == 0) {
326: next;
327: }
328: if (! $single_part) {
329: my $tmpname = $partid;
330: if ($partid =~/^\d+$/) {
331: $tmpname = $prob->part_display($partid);
332: }
333: if ($tmpname !~ /^part/) {
334: $tmpname = 'Part '.$tmpname;
335: }
336: $headers{'part'} .= qq{<th colspan="$part_span">$tmpname</th>};
337: $nonempty_part_headers = 1;
338: } else {
339: $headers{'part'} .= qq{<th colspan="$part_span"> </th>};
340: }
341: $prob_span += $part_span;
342: }
343: my $title = $prob->compTitle;
344: if ($prob_span > 0) {
345: $headers{'problem'}.= qq{<th colspan="$prob_span">$title</th>};
346: } elsif ($single_response) {
347: $prob_span = scalar(@student_columns);
348: $headers{'problem'} = qq{<th colspan="$prob_span">$title</th>};
349: }
350: }
351: if (exists($headers{'part'})) {
352: $headers{'part'} = qq{<th colspan="$student_column_count">\ </th>}.
353: $headers{'part'};
354: }
355: if (exists($headers{'response'})) {
356: $headers{'response'}=
357: qq{<th colspan="$student_column_count">\ </th>}.
358: $headers{'response'};
359: }
360: my $full_header = $/.'<table>'.$/;
361: $full_header .= '<tr align="left">'.$headers{'problem'}.'</tr>'.$/;
362: if ($nonempty_part_headers) {
363: $full_header .= '<tr align="left">'.$headers{'part'}.'</tr>'.$/;
364: }
365: $full_header .= '<tr align="left">'.$headers{'response'}.'</tr>'.$/;
366: $full_header .= '<tr align="left">'.$headers{'student'}.'</tr>'.$/;
367: #
368: # Main loop
369: my $count;
370: $r->print($/.$full_header.$/);
371: my $row_class = 'odd'; # css
372: foreach my $student (@$students) {
373: my $student_row_data;
374: if ($count++ >= 30) {
375: $r->print('</table>'.$/.$full_header.$/);
376: $count = 0;
377: }
378: last if ($c->aborted());
379: if ($show_named) {
380: foreach my $field (@student_columns) {
381: $student_row_data .= '<td valign="top">';
382: # handle comments like in lonstudentassessment.pm
383: if($field eq 'comments') {
384: $student_row_data .=
385: '<a href="/adm/'.$student->{'domain'}.'/'.
386: $student->{'username'}.'/'.'aboutme#coursecomment">'.&mt('Comments').'</a>';
387: } else {
388: $student_row_data .= $student->{$field};
389: }
390: $student_row_data .= '</td>';
391: }
392: } else {
393: my $anonid = &Crypt::PasswdMD5::unix_md5_crypt($student->{'username'},
394: $salt);
395: $anonid = substr($anonid,length($salt)+1);
396: $student_row_data = '<td valign="top" colspan="'.$student_column_count.'">'.
397: $anonid.'</td>';
398: }
399: #
400: # Figure out what it is we need to output for this student
401: my @essays;
402: my %prob_data;
403: my $maxrow;
404: foreach my $prob (@$problems) {
405: $prob_data{$prob->symb}={};
406: foreach my $partid (@{$prob->parts}) {
407: my @responses = $prob->responseIds($partid);
408: my @response_type = $prob->responseType($partid);
409: for (my $i=0;$i<=$#responses;$i++) {
410: my $respid = $responses[$i];
411: my $results =
412: &Apache::loncoursedata::get_response_data_by_student
413: ($student,$prob->symb(),$respid);
414: my $resptype = $response_type[$i];
415: my @headers = &get_headers($prob,$partid,$respid,
416: $resptype,
417: $problem_analysis{$prob->src},
418: 'html','normal',
419: @extra_resp_headers);
420: my $width = scalar(@headers);
421: next if ($width < 1);
422: my $resp_data;
423: $resp_data->{'fake'} = qq{<td colspan="$width"> </td>};
424: if (! defined($results)) {
425: $results = [];
426: }
427: #
428: if (scalar(@$results) > $maxrow && $resptype ne 'essay') {
429: $maxrow = scalar(@$results);
430: }
431: for (my $j=scalar(@$results)-1;$j>=0;$j--) {
432: if ($env{'form.all_sub'} ne 'true') {
433: next if ($j ne scalar(@$results)-1);
434: }
435: my $response = &hashify_response($results->[$j],
436: $prob,
437: $student,
438: $partid,
439: $respid);
440: if ($resptype eq 'essay') {
441: push(@essays,
442: &html_essay_results(\@headers,
443: $prob,$partid,$respid,
444: $response,
445: $single_response).
446: '</td>');
447: } elsif (lc($resptype) eq 'task') {
448: my $results =
449: &html_task_results(\@headers,
450: $prob,$partid,$respid,
451: $response,$resptype);
452: if ($results) {
453: push(@{$resp_data->{'real'}},$results);
454: }
455: } else {
456: push(@{$resp_data->{'real'}},
457: &html_non_essay_results(\@headers,
458: $prob,$partid,$respid,
459: $response,$resptype));
460: }
461: }
462: $prob_data{$prob->symb}->{$partid}->{$respid}=$resp_data;
463: } # end of $i loop
464: } # end of partid loop
465: } # end of prob loop
466: #
467: # if there is no data, skip this student.
468: next if (! $maxrow && ! scalar(@essays));
469: #
470: # Go through the problem data and output a row.
471: if ($row_class eq 'even') {
472: $row_class = 'odd';
473: } else {
474: $row_class = 'even';
475: }
476: my $printed_something;
477: for (my $rows_output = 0;$rows_output<$maxrow;$rows_output++) {
478: my $html;
479: my $no_data = 1;
480: foreach my $prob (@$problems) {
481: foreach my $partid (@{$prob->parts}) {
482: my @responses = $prob->responseIds($partid);
483: my @response_type = $prob->responseType($partid);
484: for (my $i=0;$i<=$#responses;$i++) {
485: my $respid = $responses[$i];
486: my $resp_data =
487: $prob_data{$prob->symb}->{$partid}->{$respid};
488: next if ($response_type[$i] eq 'essay');
489: if (defined($resp_data->{'real'}->[$rows_output])) {
490: $html .= $resp_data->{'real'}->[$rows_output];
491: $no_data = 0;
492: } else {
493: $html .= $resp_data->{'fake'};
494: }
495: }
496: }
497: }
498: if (! $no_data) {
499: $r->print(qq{<tr class="$row_class">$student_row_data$html</tr>}.$/);
500: $printed_something=1;
501: }
502: }
503: if (@essays) {
504: my $tr = qq{<tr class="$row_class">};
505: my $td = qq{<td valign="top" class="essay" colspan="$total_col">};
506: if (! $printed_something) {
507: $r->print($tr.$student_row_data.'</tr>'.$/);
508: }
509: $r->print($tr.$td.
510: join('</td></tr>'.$/.$tr.$td,@essays).'</td></tr>'.$/);
511: undef(@essays);
512: }
513: } # end of student loop
514: $r->print('</table>'.$/);
515: return;
516: }
517:
518: sub hashify_response {
519: my ($response,$prob,$student,$partid,$respid) =@_;
520: my $resp_hash = {};
521: if ($env{'form.correctans'} eq 'true') {
522: $resp_hash->{'Correct'} =
523: &Apache::lonstathelpers::get_student_answer
524: ($prob,$student->{'username'},$student->{'domain'},
525: $partid,$respid);
526: }
527: $resp_hash->{'Submission'} =
528: $response->[&Apache::loncoursedata::RDs_submission()];
529: $resp_hash->{'Time'} =
530: $response->[&Apache::loncoursedata::RDs_timestamp()];
531: $resp_hash->{'Attempt'} =
532: $response->[&Apache::loncoursedata::RDs_tries()];
533: $resp_hash->{'Awarded'} =
534: $response->[&Apache::loncoursedata::RDs_awarded()];
535: if ($prob->is_task()) {
536: $resp_hash->{'Grader'} =
537: $response->[&Apache::loncoursedata::RDs_response_eval_2()];
538: if ($resp_hash->{'Attempt'} eq '0') {
539: $resp_hash->{'Attempt'} = '';
540: }
541: $resp_hash->{'Award Detail'} =
542: $response->[&Apache::loncoursedata::RDs_part_award()];
543: $resp_hash->{'Status'} =
544: $response->[&Apache::loncoursedata::RDs_response_eval()];
545: } else {
546: $resp_hash->{'Award Detail'} =
547: $response->[&Apache::loncoursedata::RDs_awarddetail()];
548: }
549:
550: return $resp_hash;
551: }
552:
553: #####################################################
554: ##
555: ## HTML helper routines
556: ##
557: #####################################################
558: sub html_essay_results {
559: my ($headers,$prob,$partid,$respid,$response,$single_response)=@_;
560: if (! ref($headers) || ref($headers) ne 'ARRAY') {
561: return '';
562: }
563: # Start of telling them what problem, part, and response
564: my $Str;
565: if (! $single_response) {
566: my $id = $prob->compTitle;
567: if (defined($partid) && $partid ne '0') {
568: $id .= ' '.$prob->part_display($partid);
569: }
570: if (defined($respid)) {
571: $id .= ' '.$respid;
572: }
573: $Str .= '<span class="LC_nobreak">'.$id.'</span>'.(' 'x4);
574: }
575: #
576: shift(@$headers); # Get rid of the Submission header
577: my $correct = '';
578: if ($headers->[0] eq 'Correct') {
579: $correct = &html_format_essay_sub($response->{'Correct'});
580: shift(@$headers);
581: }
582: $Str .= '<span class="LC_nobreak">'.
583: join('',
584: map {
585: (' 'x4).&mt($_.': [_1]',$response->{$_});
586: } @$headers).'</span>';
587: if (@$headers || ! $single_response) {
588: $Str .= '<br />';
589: }
590: $Str .= &html_format_essay_sub($response->{'Submission'});
591: #
592: if (defined($correct) && $correct !~ /^\s*$/) {
593: $Str .= '<hr /><b>'.&mt('Correct').'</b>'.$correct
594: }
595: return $Str;
596: }
597:
598: sub html_format_essay_sub {
599: my ($submission) = @_;
600: return '' if (! defined($submission) || $submission eq '');
601: $submission = &HTML::Entities::decode($submission);
602: $submission =~ s/\\\"/\"/g;
603: $submission =~ s/\\\'/\'/g;
604: $submission =~ s|\\r\\n|$/|g;
605: $submission = &HTML::Entities::encode($submission,'<>&"');
606: $submission =~ s|$/\s*$/|$/</p><p>$/|g;
607: $submission =~ s|\\||g;
608: $submission = '<p>'.$submission.'</p>';
609: return $submission;
610: }
611:
612: sub html_task_results {
613: my ($headers,$prob,$partid,$respid,$response,$resptype) = @_;
614: if (! ref($headers) || ref($headers) ne 'ARRAY' || ! scalar(@$headers)) {
615: return '';
616: }
617:
618: my @values;
619: @values = map { $response->{$_}; } @$headers;
620:
621: my $td = '<td valign="top">';
622: my $str = $td.join('</td>'.$td,@values).'</td>';
623: return $str;
624: }
625:
626: sub html_non_essay_results {
627: my ($headers,$prob,$partid,$respid,$response,$resptype) = @_;
628: if (! ref($headers) || ref($headers) ne 'ARRAY' || ! scalar(@$headers)) {
629: return '';
630: }
631: #
632: my $submission = &HTML::Entities::decode(&unescape($response->{'Submission'}));
633: return '' if (! defined($submission) || $submission eq '');
634: $submission =~ s/\\\"/\"/g;
635: $submission =~ s/\\\'/\'/g;
636: if ($resptype eq 'radiobutton') {
637: $submission = &HTML::Entities::encode($submission,'<>&"');
638: $submission =~ s/=([^=])$//;
639: $submission = '<span class="LC_nobreak">'.$submission.'</span>';
640: }
641: $response->{'Submission'} = $submission;
642: #
643: my @values;
644: if ($resptype =~ /^(option|match|rank)$/) {
645: my %submission =
646: map {
647: my ($foil,$value) = split('=',&unescape($_));
648: ($foil,$value);
649: } split('&',$response->{'Submission'});
650: my %correct;
651: if (exists($response->{'Correct'})) {
652: %correct =
653: map {
654: my ($foil,$value)=split('=',&unescape($_));
655: ($foil,$value);
656: } split('&',$response->{'Correct'});
657: }
658: #
659: foreach my $original_header (@$headers) {
660: if ($original_header =~ /^_/) {
661: # '_' denotes a foil column
662: my ($header) = ($original_header =~ m/^_(.*)$/);
663: my $option = '';
664: if ( my ($foil) = ($header =~ /(.*) Correct$/)) {
665: if (exists($correct{$foil})) {
666: $option = $correct{$foil};
667: }
668: } elsif (exists($submission{$header})) {
669: $option = $submission{$header};
670: }
671: push(@values,&HTML::Entities::encode($option));
672: } elsif ($original_header eq 'Time') {
673: push(@values,&Apache::lonlocal::locallocaltime($response->{$original_header}));
674: } else {
675: # A normal column
676: push(@values,$response->{$original_header});
677: }
678: }
679: } else {
680: @values = map { $response->{$_}; } @$headers;
681: }
682: my $td = '<td valign="top">';
683: my $str = $td.join('</td>'.$td,@values).'</td>';
684: return $str;
685: }
686:
687:
688: #########################################################
689: #########################################################
690: ##
691: ## Excel Output Routines
692: ##
693: #########################################################
694: #########################################################
695: sub prepare_excel_output {
696: my ($r,$Problems,$Students,$show_named) = @_;
697: my $c = $r->connection();
698: my $salt = '$1$'.$Apache::lonnet::perlvar{'AnonymousSalt'};
699: #
700: #
701: # Determine the number of columns in the spreadsheet
702: my $columncount = 3; # username, domain, id
703: my @extra_resp_headers = &get_extra_response_headers();
704: my $lastprob;
705: my %problem_analysis;
706: foreach my $prob (@$Problems) {
707: my %analysis = &Apache::lonstathelpers::get_problem_data($prob->src);
708: $problem_analysis{$prob->src}=\%analysis;
709: foreach my $partid (@{$prob->parts}) {
710: my $responses = [$prob->responseIds($partid)];
711: my $resptypes = [$prob->responseType($partid)];
712: for (my $i=0;$i<scalar(@$responses);$i++) {
713: my @headers = &get_headers($prob,$partid,$responses->[$i],
714: $resptypes->[$i],
715: $problem_analysis{$prob->src},
716: 'excel','display',
717: @extra_resp_headers);
718: $columncount += scalar(@headers);
719: }
720: }
721: last if ($columncount > 255);
722: $lastprob = $prob;
723: }
724: if ($columncount > 255) {
725: $r->print('<h1>'.&mt('Unable to complete request').'</h1>'.$/.
726: '<p>'.&mt('LON-CAPA is unable to produce your Excel spreadsheet because your selections will result in more than 255 columns. Excel allows only 255 columns in a spreadsheet.').'</p>'.$/.
727: '<p>'.&mt('Consider selecting fewer problems to generate reports on, or reducing the number of items per problem. Or use HTML or CSV output.').'</p>'.$/.
728: '<p>'.&mt('The last problem that will fit in the current spreadsheet is [_1].',$lastprob->compTitle).'</p>');
729: $r->rflush();
730: return;
731: }
732: #
733: # Print out a message telling them what we are doing
734: if (scalar(@$Problems) > 1) {
735: $r->print('<h2>'.
736: &mt('Preparing Excel spreadsheet of student responses to [_1] problems',
737: scalar(@$Problems)).
738: '</h2>');
739: } else {
740: $r->print('<h2>'.
741: &mt('Preparing Excel spreadsheet of student responses').
742: '</h2>');
743: }
744: $r->rflush();
745: #
746: # Create the excel spreadsheet
747: my ($workbook,$filename,$format) =
748: &Apache::loncommon::create_workbook($r);
749: return if (! defined($workbook));
750: my $worksheet = $workbook->addworksheet('Student Submission Data');
751: #
752: # Add headers to the worksheet
753: my $rows_output = 0;
754: $worksheet->write($rows_output++,0,
755: $env{'course.'.$env{'request.course.id'}.'.description'},
756: $format->{'h1'});
757: $rows_output++;
758: my $cols_output = 0;
759: my $title_row = $rows_output++;
760: my $partid_row = $rows_output++;
761: my $respid_row = $rows_output++;
762: my $header_row = $rows_output++;
763: $worksheet->write($title_row ,0,'Problem Title',$format->{'bold'});
764: $worksheet->write($partid_row,0,'Part ID',$format->{'bold'});
765: $worksheet->write($respid_row,0,'Response ID',$format->{'bold'});
766: # Student headers
767: my @StudentColumns;
768: if ($show_named) {
769: @StudentColumns = qw(username domain id section);
770: } else {
771: @StudentColumns = qw(username);
772: }
773: foreach (@StudentColumns) {
774: $worksheet->write($header_row,$cols_output++,ucfirst($_),
775: $format->{'bold'});
776: }
777: # Problem headers
778: my %start_col;
779: foreach my $prob (@$Problems) {
780: my $title = $prob->compTitle;
781: $worksheet->write($title_row,$cols_output,
782: $title,$format->{'h3'});
783: foreach my $partid (@{$prob->parts}) {
784: $worksheet->write($partid_row,$cols_output,
785: $prob->part_display($partid));
786: my $responses = [$prob->responseIds($partid)];
787: my $resptypes = [$prob->responseType($partid)];
788: for (my $i=0;$i<scalar(@$responses);$i++) {
789: $start_col{$prob->symb}->{$partid}->{$responses->[$i]}=
790: $cols_output;
791: $worksheet->write($respid_row,$cols_output,
792: $resptypes->[$i].', '.$responses->[$i]);
793: my @headers = &get_headers($prob,$partid,$responses->[$i],
794: $resptypes->[$i],
795: $problem_analysis{$prob->src},
796: 'excel','display',
797: @extra_resp_headers);
798: foreach my $text (@headers) {
799: if ($text eq 'Time') {
800: $worksheet->set_column($cols_output,$cols_output,undef,
801: $format->{'date'});
802: }
803: $worksheet->write($header_row,$cols_output++,$text);
804: }
805: }
806: }
807: }
808: #
809: # Populate the worksheet with the student data
810: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
811: ($r,'Excel File Compilation Status',
812: 'Excel File Compilation Progress',
813: scalar(@$Students),'inline',undef,'Statistics','stats_status');
814: my $max_row = $rows_output;
815: foreach my $student (@$Students) {
816: last if ($c->aborted());
817: $cols_output = 0;
818: my $student_row = $max_row;
819: my $anonid = &Crypt::PasswdMD5::unix_md5_crypt($student->{'username'},
820: $salt);
821: $anonid = substr($anonid,length($salt)+1);
822: foreach my $field (@StudentColumns) {
823: if ($show_named) {
824: $worksheet->write($student_row,$cols_output++,
825: $student->{$field});
826: } else {
827: $worksheet->write($student_row,$cols_output++,
828: $anonid);
829: }
830: }
831: my $last_student_col = $cols_output-1;
832: foreach my $prob (@$Problems) {
833: foreach my $partid (@{$prob->parts}) {
834: my @Response = $prob->responseIds($partid);
835: my @ResponseType = $prob->responseType($partid);
836: for (my $i=0;$i<=$#Response;$i++) {
837: my $respid = $Response[$i];
838: my $resptype = $ResponseType[$i];
839: my $results =
840: &Apache::loncoursedata::get_response_data_by_student
841: ($student,$prob->symb(),$respid);
842: my @headers = &get_headers($prob,$partid,$respid,
843: $resptype,
844: $problem_analysis{$prob->src},
845: 'excel','normal',
846: @extra_resp_headers);
847:
848: if (! defined($results)) {
849: $results = [];
850: }
851: #
852: $rows_output = $student_row;
853: #
854: my $response_start_col = $start_col{$prob->symb}->{$partid}->{$respid};
855: for (my $j=scalar(@$results)-1;$j>=0;$j--) {
856: $cols_output = $response_start_col;
857: if ($env{'form.all_sub'} ne 'true') {
858: next if ($j ne scalar(@$results)-1);
859: }
860: my $response = &hashify_response($results->[$j],
861: $prob,
862: $student,
863: $partid,
864: $respid);
865: my @response_data =
866: &compile_response_data(\@headers,$response,
867: $prob,$partid,$respid,
868: $resptype,
869: \&excel_format_item);
870: $worksheet->write_row($rows_output++,$cols_output,
871: \@response_data);
872: $cols_output+=scalar(@response_data);
873: if ($rows_output > $max_row) {
874: $max_row = $rows_output;
875: }
876: }
877: }
878: }
879: }
880: # Fill in the remaining rows with the students data
881: for (my $row = $student_row+1;$row<$max_row;$row++) {
882: my $cols = 0;
883: foreach my $field (@StudentColumns) {
884: if ($show_named) {
885: $worksheet->write($row,$cols++,
886: $student->{$field});
887: } else {
888: $worksheet->write($row,$cols++,
889: $anonid);
890: }
891: }
892: }
893: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
894: 'last student');
895: }
896: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
897: #
898: # Close the excel file
899: $workbook->close();
900: #
901: # Write a link to allow them to download it
902: $r->print('<p><a href="'.$filename.'">'.
903: &mt('Your Excel spreadsheet.').
904: '</a></p>'."\n");
905: $r->print('<script>'.
906: 'window.document.Statistics.stats_status.value="'.
907: 'Done compiling spreadsheet. See link below to download.'.
908: '";</script>');
909: $r->rflush();
910: return;
911: }
912:
913: sub compile_response_data {
914: my ($headers,$response,$prob,$partid,$respid,$resptype,$format) = @_;
915: if (! ref($headers) || ref($headers) ne 'ARRAY' || ! scalar(@$headers)) {
916: return ();
917: }
918: if (ref($format) ne 'CODE') {
919: $format = sub { return $_[0]; };
920: }
921: #
922: my $submission =
923: &HTML::Entities::decode
924: (&unescape($response->{'Submission'}));
925: if (!$prob->is_task()) {
926: return () if (! defined($submission) || $submission eq '');
927: }
928: $submission =~ s/\\\"/\"/g;
929: $submission =~ s/\\\'/\'/g;
930: if ($resptype eq 'radiobutton') {
931: $submission =~ s/=([^=])$//;
932: }
933: $response->{'Submission'} = $submission;
934: #
935: my @values;
936: if ($resptype =~ /^(option|match|rank)$/) {
937: my %submission =
938: map {
939: my ($foil,$value) = split('=',&unescape($_));
940: ($foil,$value);
941: } split('&',$response->{'Submission'});
942: my %correct;
943: if (exists($response->{'Correct'})) {
944: %correct =
945: map {
946: my ($foil,$value)=split('=',&unescape($_));
947: ($foil,$value);
948: } split('&',$response->{'Correct'});
949: }
950: #
951: foreach my $original_header (@$headers) {
952: if ($original_header =~ /^_/) {
953: # '_' denotes a foil column
954: my ($header) = ($original_header =~ m/^_(.*)$/);
955: my $option = '';
956: if ( my ($foil) = ($header =~ /(.*) Correct$/)) {
957: if (exists($correct{$foil})) {
958: $option = $correct{$foil};
959: }
960: } elsif (exists($submission{$header})) {
961: $option = $submission{$header};
962: }
963: push(@values,&{$format}($option,$header));
964: } else {
965: # A normal column
966: push(@values,&{$format}($response->{$original_header},
967: $original_header));
968: }
969: }
970: } else {
971: @values = map { &{$format}($response->{$_},$_); } @$headers;
972: }
973: return @values;
974: }
975:
976: sub excel_format_item {
977: my ($item,$type) = @_;
978: if ($type eq 'Time') {
979: $item = &Apache::lonstathelpers::calc_serial($item);
980: } else {
981: if ($item =~ m/^=/) {
982: $item = ' '.$item;
983: }
984: $item =~ s/\\r//g;
985: $item =~ s/\\n/\n/g;
986: $item =~ s/(\s*$|^\s*)//g;
987: $item =~ s/\\\'/\'/g;
988: }
989: return $item;
990: }
991:
992: #########################################################
993: #########################################################
994: ##
995: ## CSV output of student answers
996: ##
997: #########################################################
998: #########################################################
999: sub prepare_csv_output {
1000: my ($r,$problems,$students,$show_named) = @_;
1001: my $c = $r->connection();
1002: my $salt = '$1$'.$Apache::lonnet::perlvar{'AnonymousSalt'};
1003: #
1004: $r->print('<h2>'.
1005: &mt('Generating CSV report of student responses').'</h2>');
1006: #
1007: # Progress window
1008: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
1009: ($r,'CSV File Compilation Status',
1010: 'CSV File Compilation Progress',
1011: scalar(@$students),'inline',undef,'Statistics','stats_status');
1012:
1013: $r->rflush();
1014: #
1015: # Open a file
1016: my $outputfile;
1017: my $filename = '/prtspool/'.
1018: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1019: time.'_'.rand(1000000000).'.csv';
1020: unless ($outputfile = Apache::File->new('>/home/httpd'.$filename)) {
1021: $r->log_error("Couldn't open $filename for output $!");
1022: $r->print('<div class="LC_error">'
1023: .&mt('Problems occurred in writing the CSV file. '
1024: .'This error has been logged. '
1025: .'Please alert your LON-CAPA administrator.')
1026: .'</div>');
1027: $outputfile = undef;
1028: }
1029: #
1030: # Compute the number of columns per response
1031: my @extra_resp_headers = &get_extra_response_headers($show_named);
1032: #
1033: # Create the table header
1034: my @student_columns;
1035: if ($show_named) {
1036: @student_columns = qw(username domain id section);
1037: } else {
1038: @student_columns = qw(username);
1039: }
1040: #
1041: my %headers;
1042: push(@{$headers{'student'}},@student_columns);
1043: # Pad for the student data
1044: foreach my $row ('problem','part','response') {
1045: $headers{$row}=[map {''} @student_columns];
1046: }
1047: #
1048: # we put the headers into the %headers hash
1049: my %problem_analysis;
1050: my %start_col;
1051: my $max_column = scalar(@student_columns);
1052: foreach my $prob (@$problems) {
1053: my %analysis = &Apache::lonstathelpers::get_problem_data($prob->src);
1054: $problem_analysis{$prob->src}=\%analysis;
1055: $headers{'problem'}->[$max_column] = $prob->compTitle;
1056: foreach my $partid (@{$prob->parts}) {
1057: $headers{'part'}->[$max_column] = $prob->part_display($partid);
1058: my $responses = [$prob->responseIds($partid)];
1059: my $resptypes = [$prob->responseType($partid)];
1060: for (my $i=0;$i<scalar(@$responses);$i++) {
1061: my @headers = &get_headers($prob,$partid,$responses->[$i],
1062: $resptypes->[$i],
1063: $problem_analysis{$prob->src},
1064: 'csv','display',
1065: @extra_resp_headers);
1066: $start_col{$prob->symb}->{$partid}->{$responses->[$i]}=
1067: $max_column;
1068: $headers{'response'}->[$max_column]=
1069: &mt('Response [_1]',$responses->[$i]);
1070: for (my $j=0;$j<=$#headers;$j++) {
1071: $headers{'student'}->[$max_column+$j]=$headers[$j];
1072: }
1073: $max_column += scalar(@headers);
1074: }
1075: }
1076: }
1077: foreach my $row ('problem','part','response','student') {
1078: print $outputfile '"'.
1079: join('","',
1080: map {
1081: &Apache::loncommon::csv_translate($_);
1082: } @{$headers{$row}}).'"'.$/;
1083: }
1084: #
1085: # Main loop
1086: foreach my $student (@$students) {
1087: last if ($c->aborted());
1088: my $anonid = &Crypt::PasswdMD5::unix_md5_crypt($student->{'username'},
1089: $salt);
1090: $anonid = substr($anonid,length($salt)+1);
1091: my @rows;
1092: foreach my $prob (@$problems) {
1093: foreach my $partid (@{$prob->parts}) {
1094: my @responses = $prob->responseIds($partid);
1095: my @response_type = $prob->responseType($partid);
1096: for (my $i=0;$i<=$#responses;$i++) {
1097: my $respid = $responses[$i];
1098: my $resptype = $response_type[$i];
1099: my @headers = &get_headers($prob,$partid,$respid,$resptype,
1100: $problem_analysis{$prob->src},
1101: 'csv','normal',
1102: @extra_resp_headers);
1103: my $results =
1104: &Apache::loncoursedata::get_response_data_by_student
1105: ($student,$prob->symb(),$respid);
1106: if (! defined($results)) {
1107: $results = [];
1108: }
1109: for (my $j=0; $j<scalar(@$results);$j++) {
1110: if ($env{'form.all_sub'} ne 'true') {
1111: next if ($j != 0);
1112: }
1113: my $idx = scalar(@$results) - $j - 1;
1114: my $response = &hashify_response($results->[$idx],
1115: $prob,$student,
1116: $partid,$respid);
1117: my @data = &compile_response_data(\@headers,$response,
1118: $prob,$partid,
1119: $respid,$resptype,
1120: \&csv_format_item);
1121: my $resp_start_idx =
1122: $start_col{$prob->symb}->{$partid}->{$respid};
1123: for (my $k=0;$k<=$#data;$k++) {
1124: $rows[$j]->[$resp_start_idx + $k] = $data[$k];
1125: }
1126: }
1127: }
1128: }
1129: }
1130: foreach my $row (@rows) {
1131: my $student_row_data = '';
1132: if ($show_named) {
1133: $student_row_data = '"'.join('","',
1134: map { $student->{$_}; }
1135: @student_columns).'"';
1136: } else {
1137: $student_row_data = '"'.$anonid.'"';
1138: }
1139: print $outputfile $student_row_data;
1140: for (my $i=scalar(@student_columns);$i<$max_column;$i++) {
1141: my $value = &Apache::loncommon::csv_translate($row->[$i]);
1142: $value ||='';
1143: print $outputfile ',"'.$value.'"';
1144: }
1145: print $outputfile $/;
1146: }
1147: undef(@rows);
1148: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
1149: 'last student');
1150: }
1151: close($outputfile);
1152: #
1153: # Close the progress window
1154: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1155: #
1156: # Tell the user where to get their CSV file
1157: $r->print('<br />'.
1158: '<a href="'.$filename.'">'.&mt('Your CSV file.').'</a>'."\n");
1159: $r->rflush();
1160: return;
1161: }
1162:
1163: sub csv_format_item {
1164: my ($item,$type) = @_;
1165: if ($type eq 'Time') {
1166: $item = localtime($item);
1167: }
1168: $item =&Apache::loncommon::csv_translate($item);
1169: return $item;
1170: }
1171:
1172: #########################################################
1173: #########################################################
1174: ##
1175: ## Generic Interface Routines
1176: ##
1177: #########################################################
1178: #########################################################
1179: sub CreateInterface {
1180: ##
1181: ## Output Selection
1182: my $output_selector = $/.'<select name="output">'.$/;
1183: foreach ('HTML','Excel','CSV') {
1184: $output_selector .= ' <option value="'.lc($_).'"';
1185: if ($env{'form.output'} eq lc($_)) {
1186: $output_selector .= ' selected="selected" ';
1187: }
1188: $output_selector .='>'.&mt($_).'</option>'.$/;
1189: }
1190: $output_selector .= '</select>'.$/;
1191: ##
1192: ## Environment variable initialization
1193: my $Str = '';
1194: $Str .= &Apache::lonhtmlcommon::breadcrumbs('Student Submission Reports');
1195: $Str .= '<br />';
1196: $Str .= &Apache::loncommon::start_data_table();
1197: $Str .= &Apache::loncommon::start_data_table_header_row();
1198: $Str .= '<th>'.&mt('Sections').'</th>';
1199: $Str .= '<th>'.&mt('Groups').'</th>';
1200: $Str .= '<th>'.&mt('Access Status').'</th>';
1201: $Str .= '<th>'.&mt('Options').'</th>';
1202: $Str .= '<th>'.&mt('Output Format').'</th>';
1203: $Str .= &Apache::loncommon::end_data_table_header_row();
1204: #
1205: $Str .= &Apache::loncommon::start_data_table_row();
1206: $Str .= '<td align="center">'."\n";
1207: $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
1208: $Str .= '</td>';
1209: #
1210: $Str .= '<td align="center">'."\n";
1211: $Str .= &Apache::lonstatistics::GroupSelect('Group','multiple',5);
1212: $Str .= '</td>';
1213: #
1214: $Str .= '<td align="center">';
1215: $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
1216: $Str .= '</td>';
1217: #
1218: # Render problem checkbox
1219: my $prob_checkbox = '<input type="checkbox" name="renderprob" ';
1220: if (exists($env{'form.renderprob'}) && $env{'form.renderprob'} eq 'true') {
1221: $prob_checkbox .= 'checked="checked" ';
1222: }
1223: $prob_checkbox .= 'value="true" />';
1224: #
1225: # Compute correct answers checkbox
1226: my $ans_checkbox = '<input type="checkbox" name="correctans" ';
1227: if (exists($env{'form.correctans'}) && $env{'form.correctans'} eq 'true') {
1228: $ans_checkbox .= 'checked="checked" ';
1229: }
1230: $ans_checkbox .= 'value="true" />';
1231: #
1232: # Show all submissions checkbox
1233: my $all_sub_checkbox = '<input type="checkbox" name="all_sub" ';
1234: if (exists($env{'form.all_sub'}) &&
1235: $env{'form.all_sub'} eq 'true') {
1236: $all_sub_checkbox .= 'checked="checked" ';
1237: }
1238: $all_sub_checkbox.= 'value="true" />';
1239: #
1240: # problem status checkbox
1241: my $prob_status_checkbox = '<input type="checkbox" name="prob_status" ';
1242: if (exists($env{'form.prob_status'}) &&
1243: $env{'form.prob_status'} eq 'true') {
1244: $prob_status_checkbox .= 'checked="checked" ';
1245: }
1246: $prob_status_checkbox .= 'value="true" />';
1247: #
1248: $Str .= '<td align="right" valign="top">'.
1249: '<label><b>'.
1250: &mt('Show problem').' '.$prob_checkbox.'</b></label><br />'.
1251: '<label><b>'.
1252: &mt('Show correct answers').' '.$ans_checkbox.'</b></label><br />'.
1253: '<label><b>'.
1254: &mt('Show all submissions').' '.$all_sub_checkbox.
1255: '</b></label><br />'.
1256: '<label><b>'.
1257: &mt('Show problem grading').' '.$prob_status_checkbox.
1258: '</b></label><br />'.
1259: '</td>';
1260: #
1261: $Str .= '<td align="center" valign="top">'.$output_selector.'</td>';
1262: #
1263: $Str .= &Apache::loncommon::end_data_table_row();
1264: $Str .= &Apache::loncommon::end_data_table();
1265: #
1266: $Str .= '<p><span class="LC_nobreak">'
1267: .&mt('Status: [_1]',
1268: '<input type="text" name="stats_status"'
1269: .' size="60" value="" readonly="readonly" />')
1270: .'</span></p>';
1271: ##
1272: return $Str;
1273: }
1274:
1275: 1;
1276:
1277: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>