Annotation of loncom/interface/statistics/lonstathelpers.pm, revision 1.25
1.1 matthew 1: # The LearningOnline Network with CAPA
2: #
1.25 ! matthew 3: # $Id: lonstathelpers.pm,v 1.24 2004/09/23 14:35:25 matthew Exp $
1.1 matthew 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: ####################################################
28: ####################################################
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonstathelpers - helper routines used by statistics
35:
36: =head1 SYNOPSIS
37:
38: This module provides a place to consolidate much of the statistics
39: routines that are needed across multiple statistics functions.
40:
41: =head1 OVERVIEW
42:
43: =over 4
44:
45: =cut
46:
47: ####################################################
48: ####################################################
49: package Apache::lonstathelpers;
50:
51: use strict;
52: use Apache::lonnet();
53: use Apache::loncommon();
54: use Apache::lonhtmlcommon();
55: use Apache::loncoursedata();
56: use Apache::lonstatistics;
57: use Apache::lonlocal;
58: use HTML::Entities();
59: use Time::Local();
60: use Spreadsheet::WriteExcel();
1.8 matthew 61: use GDBM_File;
62: use Storable qw(freeze thaw);
1.1 matthew 63:
64: ####################################################
65: ####################################################
66:
67: =pod
68:
69: =item &render_resource($resource)
70:
71: Input: a resource generated from
72: &Apache::loncoursedata::get_sequence_assessment_data().
73:
74: Retunrs: a scalar containing html for a rendering of the problem
75: within a table.
76:
77: =cut
78:
79: ####################################################
80: ####################################################
81: sub render_resource {
82: my ($resource) = @_;
83: ##
84: ## Render the problem
85: my $base;
86: ($base,undef) = ($resource->{'src'} =~ m|(.*/)[^/]*$|);
87: $base = "http://".$ENV{'SERVER_NAME'}.$base;
88: my $rendered_problem =
89: &Apache::lonnet::ssi_body($resource->{'src'});
90: $rendered_problem =~ s/<\s*form\s*/<nop /g;
91: $rendered_problem =~ s|(<\s*/form\s*>)|<\/nop>|g;
92: return '<table bgcolor="ffffff"><tr><td>'.
93: '<base href="'.$base.'" />'.
94: $rendered_problem.
95: '</td></tr></table>';
96: }
1.2 matthew 97:
98: ####################################################
99: ####################################################
100:
101: =pod
102:
103: =item &ProblemSelector($AcceptedResponseTypes)
104:
105: Input: scalar containing regular expression which matches response
106: types to show. '.' will yield all, '(option|radiobutton)' will match
107: all option response and radiobutton problems.
108:
109: Returns: A string containing html for a table which lists the sequences
110: and their contents. A radiobutton is provided for each problem.
1.14 matthew 111: Skips 'survey' problems.
1.2 matthew 112:
113: =cut
114:
115: ####################################################
116: ####################################################
117: sub ProblemSelector {
118: my ($AcceptedResponseTypes) = @_;
119: my $Str;
120: $Str = "\n<table>\n";
1.12 matthew 121: foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess('all')) {
1.2 matthew 122: next if ($seq->{'num_assess'}<1);
123: my $seq_str = '';
124: foreach my $res (@{$seq->{'contents'}}) {
125: next if ($res->{'type'} ne 'assessment');
126: foreach my $part (@{$res->{'parts'}}) {
127: my $partdata = $res->{'partdata'}->{$part};
128: for (my $i=0;$i<scalar(@{$partdata->{'ResponseTypes'}});$i++){
129: my $respid = $partdata->{'ResponseIds'}->[$i];
130: my $resptype = $partdata->{'ResponseTypes'}->[$i];
131: if ($resptype =~ m/$AcceptedResponseTypes/) {
132: my $value = &make_target_id({symb=>$res->{'symb'},
133: part=>$part,
134: respid=>$respid,
135: resptype=>$resptype});
136: my $checked = '';
137: if ($ENV{'form.problemchoice'} eq $value) {
138: $checked = 'checked ';
139: }
140: my $title = $res->{'title'};
141: if (! defined($title) || $title eq '') {
142: ($title) = ($res->{'src'} =~ m:/([^/]*)$:);
143: }
144: $seq_str .= '<tr><td>'.
145: '<input type="radio" name="problemchoice" value="'.$value.'" '.$checked.'/>'.
146: '</td><td>'.
147: $resptype.'</td><td>'.
148: '<a href="'.$res->{'src'}.'">'.$title.'</a> ';
149: # '<a href="'.$res->{'src'}.'">'.$resptype.' '.$res->{'title'}.'</a> ';
1.5 matthew 150: if (scalar(@{$partdata->{'ResponseIds'}}) > 1) {
1.2 matthew 151: $seq_str .= &mt('response').' '.$respid;
152: }
153: $seq_str .= "</td></tr>\n";
154: }
155: }
156: }
157: }
158: if ($seq_str ne '') {
159: $Str .= '<tr><td> </td><td colspan="2"><b>'.$seq->{'title'}.'</b></td>'.
160: "</tr>\n".$seq_str;
161: }
162: }
163: $Str .= "</table>\n";
164: return $Str;
165: }
166:
167: ####################################################
168: ####################################################
169:
170: =pod
171:
1.24 matthew 172: =item &MultipleProblemSelector($navmap,$selected,$inputname)
1.21 matthew 173:
174: Generate HTML with checkboxes for problem selection.
175:
176: Input:
177:
178: $navmap: a navmap object. If undef, navmaps will be called to create a
179: new object.
180:
181: $selected: Scalar, Array, or hash reference of currently selected items.
182:
183: $inputname: The name of the form elements to use for the checkboxs.
184:
185: Returns: A string containing html for a table which lists the sequences
186: and their contents. A checkbox is provided for each problem.
187:
188: =cut
189:
190: ####################################################
191: ####################################################
192: sub MultipleProblemSelector {
1.23 matthew 193: my ($navmap,$inputname,$formname)=@_;
1.21 matthew 194: my $cid = $ENV{'request.course.id'};
195: my $Str;
196: # Massage the input as needed.
197: if (! defined($navmap)) {
198: $navmap = Apache::lonnavmaps::navmap->new();
199: if (! defined($navmap)) {
200: $Str .=
201: '<h1>'.&mt('Error: cannot process course structure').'</h1>';
202: return $Str;
203: }
204: }
205: my $selected = {map { ($_,1) } (&get_selected_symbs($inputname))};
206: # Header
207: $Str .= <<"END";
1.25 ! matthew 208: <script language="JavaScript" type="text/javascript">
! 209: function checkall(value,seqid) {
1.21 matthew 210: for (i=0; i<document.forms.$formname.elements.length; i++) {
211: ele = document.forms.$formname.elements[i];
212: if (ele.name == '$inputname') {
1.25 ! matthew 213: if (seqid != null) {
! 214: itemid = document.forms.$formname.elements[i].id;
! 215: thing = itemid.split(':');
! 216: if (thing[0] == seqid) {
! 217: document.forms.$formname.elements[i].checked=value;
! 218: }
! 219: } else {
! 220: document.forms.$formname.elements[i].checked=value;
! 221: }
1.21 matthew 222: }
223: }
224: }
225: </script>
226: END
227: $Str .=
228: '<a href="javascript:checkall(true)">'.&mt('Select All').'</a>'.
229: (' 'x4).
230: '<a href="javascript:checkall(false)">'.&mt('Unselect All').'</a>';
231: $Str .= $/.'<table>'.$/;
232: my $iterator = $navmap->getIterator(undef, undef, undef, 1);
233: my $sequence_string;
1.25 ! matthew 234: my $seq_id = 0;
1.21 matthew 235: my @Accumulator = (&new_accumulator($ENV{'course.'.$cid.'.description'},
236: '',
237: '',
1.25 ! matthew 238: $seq_id++,
1.21 matthew 239: $inputname));
240: my @Sequence_Data;
241: while (my $curRes = $iterator->next()) {
242: if ($curRes == $iterator->END_MAP) {
243: if (ref($Accumulator[-1]) eq 'CODE') {
1.24 matthew 244: my $old_accumulator = pop(@Accumulator);
245: push(@Sequence_Data,&{$old_accumulator}());
1.21 matthew 246: }
247: } elsif ($curRes == $iterator->BEGIN_MAP) {
248: # Not much to do here.
249: }
250: next if (! ref($curRes));
251: if ($curRes->is_map) {
1.24 matthew 252: push(@Accumulator,&new_accumulator($curRes->compTitle,
1.21 matthew 253: $curRes->src,
254: $curRes->symb,
1.25 ! matthew 255: $seq_id++,
1.21 matthew 256: $inputname));
257: } elsif ($curRes->is_problem) {
258: if (@Accumulator && $Accumulator[-1] ne '') {
259: &{$Accumulator[-1]}($curRes,
260: exists($selected->{$curRes->symb}));
261: }
262: }
263: }
264: my $course_seq = pop(@Sequence_Data);
265: foreach my $seq ($course_seq,@Sequence_Data) {
266: #my $seq = pop(@Sequence_Data);
267: next if (! defined($seq) || ref($seq) ne 'HASH');
268: $Str.= '<tr><td colspan="2">'.
1.25 ! matthew 269: '<b>'.$seq->{'title'}.'</b>'.(' 'x2).
! 270: '<a href="javascript:checkall(true,'.$seq->{'id'}.')">'.
! 271: &mt('Select').'</a>'.(' 'x2).
! 272: '<a href="javascript:checkall(false,'.$seq->{'id'}.')">'.
! 273: &mt('Unselect').'</a>'.(' 'x2).
1.21 matthew 274: '</td></tr>'.$/;
275: $Str.= $seq->{'html'};
276: }
277: $Str .= '</table>'.$/;
278: return $Str;
279: }
280:
281: sub get_title {
282: my ($title,$src) = @_;
283: if ($title eq '') {
284: ($title) = ($src =~ m|/([^/]+)$|);
285: } else {
286: $title =~ s/\:/:/g;
287: }
288: return $title;
289: }
290:
291: sub new_accumulator {
1.25 ! matthew 292: my ($title,$src,$symb,$seq_id,$inputname) = @_;
1.21 matthew 293: my $target;
1.25 ! matthew 294: my $item_id=0;
1.21 matthew 295: return
296: sub {
297: if (@_) {
298: my ($res,$checked) = @_;
1.23 matthew 299: $target.='<tr><td><label>'.
1.21 matthew 300: '<input type="checkbox" name="'.$inputname.'" ';
301: if ($checked) {
302: $target .= 'checked ';
303: }
1.25 ! matthew 304: $target .= 'id="'.$seq_id.':'.$item_id++.'" ';
1.21 matthew 305: $target.=
306: 'value="'.&Apache::lonnet::escape($res->symb).'" />'.
1.24 matthew 307: ' '.$res->compTitle.'</label></td>'.
1.21 matthew 308: '</tr>'.$/;
309: } else {
310: if (defined($target)) {
311: return { title => $title,
312: symb => $symb,
313: src => $src,
1.25 ! matthew 314: id => $seq_id,
1.21 matthew 315: html => $target, };
316: }
317: return undef;
318: }
319: };
320: }
321:
322: sub get_selected_symbs {
323: my ($inputfield) = @_;
324: my $field = 'form.'.$inputfield;
325: my @Symbs;
326: if (exists($ENV{$field})) {
327: if (! ref($ENV{$field})) {
328: @Symbs = (&Apache::lonnet::unescape($ENV{$field}));
329: } else {
330: @Symbs = (map {&Apache::lonnet::unescape($_);} @{$ENV{$field}});
331: }
332: }
333: return @Symbs;
334: }
335:
336: ####################################################
337: ####################################################
338:
339: =pod
340:
1.2 matthew 341: =item &make_target_id($target)
342:
343: Inputs: Hash ref with the following entries:
344: $target->{'symb'}, $target->{'part'}, $target->{'respid'},
345: $target->{'resptype'}.
346:
347: Returns: A string, suitable for a form parameter, which uniquely identifies
348: the problem, part, and response to do statistical analysis on.
349:
350: Used by Apache::lonstathelpers::ProblemSelector().
351:
352: =cut
353:
354: ####################################################
355: ####################################################
356: sub make_target_id {
357: my ($target) = @_;
358: my $id = &Apache::lonnet::escape($target->{'symb'}).':'.
359: &Apache::lonnet::escape($target->{'part'}).':'.
360: &Apache::lonnet::escape($target->{'respid'}).':'.
361: &Apache::lonnet::escape($target->{'resptype'});
362: return $id;
363: }
364:
365: ####################################################
366: ####################################################
367:
368: =pod
369:
370: =item &get_target_from_id($id)
371:
372: Inputs: $id, a scalar string from Apache::lonstathelpers::make_target_id().
373:
374: Returns: A hash reference, $target, containing the following keys:
375: $target->{'symb'}, $target->{'part'}, $target->{'respid'},
376: $target->{'resptype'}.
377:
378: =cut
379:
380: ####################################################
381: ####################################################
382: sub get_target_from_id {
383: my ($id) = @_;
1.21 matthew 384: if (! ref($id)) {
385: my ($symb,$part,$respid,$resptype) = split(':',$id);
386: return ({ symb => &Apache::lonnet::unescape($symb),
387: part => &Apache::lonnet::unescape($part),
388: respid => &Apache::lonnet::unescape($respid),
389: resptype => &Apache::lonnet::unescape($resptype)});
390: } elsif (ref($id) eq 'ARRAY') {
391: my @Return;
392: foreach my $selected (@$id) {
393: my ($symb,$part,$respid,$resptype) = split(':',$selected);
394: push(@Return,{ symb => &Apache::lonnet::unescape($symb),
395: part => &Apache::lonnet::unescape($part),
396: respid => &Apache::lonnet::unescape($respid),
397: resptype => &Apache::lonnet::unescape($resptype)});
398: }
399: return \@Return;
400: }
1.2 matthew 401: }
402:
403: ####################################################
404: ####################################################
405:
406: =pod
407:
1.13 matthew 408: =item &get_prev_curr_next($target,$AcceptableResponseTypes,$granularity)
1.2 matthew 409:
410: Determine the problem parts or responses preceeding and following the
411: current resource.
412:
413: Inputs: $target (see &Apache::lonstathelpers::get_target_from_id())
414: $AcceptableResponseTypes, regular expression matching acceptable
415: response types,
1.13 matthew 416: $granularity, either 'part', 'response', or 'part_survey'
1.2 matthew 417:
418: Returns: three hash references, $prev, $curr, $next, which refer to the
419: preceeding, current, or following problem parts or responses, depending
420: on the value of $granularity. Values of undef indicate there is no
421: previous or next part/response. A value of undef for all three indicates
422: there was no match found to the current part/resource.
423:
424: The hash references contain the following keys:
425: symb, part, resource
426:
427: If $granularity eq 'response', the following ADDITIONAL keys will be present:
428: respid, resptype
429:
430: =cut
431:
432: ####################################################
433: ####################################################
434: sub get_prev_curr_next {
435: my ($target,$AcceptableResponseTypes,$granularity) = @_;
436: #
437: # Build an array with the data we need to search through
438: my @Resource;
1.12 matthew 439: foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess('all')) {
1.2 matthew 440: foreach my $res (@{$seq->{'contents'}}) {
441: next if ($res->{'type'} ne 'assessment');
442: foreach my $part (@{$res->{'parts'}}) {
443: my $partdata = $res->{'partdata'}->{$part};
1.20 matthew 444: if ($partdata->{'Survey'} && ($granularity eq 'part_survey')){
445: push (@Resource,
446: { symb => $res->{symb},
447: part => $part,
448: resource => $res,
449: } );
1.13 matthew 450: } elsif ($granularity eq 'part') {
1.2 matthew 451: push (@Resource,
452: { symb => $res->{symb},
453: part => $part,
454: resource => $res,
455: } );
456: } elsif ($granularity eq 'response') {
457: for (my $i=0;
458: $i<scalar(@{$partdata->{'ResponseTypes'}});
459: $i++){
460: my $respid = $partdata->{'ResponseIds'}->[$i];
461: my $resptype = $partdata->{'ResponseTypes'}->[$i];
462: next if ($resptype !~ m/$AcceptableResponseTypes/);
463: push (@Resource,
464: { symb => $res->{symb},
465: part => $part,
466: respid => $partdata->{'ResponseIds'}->[$i],
467: resource => $res,
468: resptype => $resptype
469: } );
470: }
471: }
472: }
473: }
474: }
475: #
476: # Get the index of the current situation
477: my $curr_idx;
478: for ($curr_idx=0;$curr_idx<$#Resource;$curr_idx++) {
479: my $curr_item = $Resource[$curr_idx];
1.13 matthew 480: if ($granularity eq 'part' || $granularity eq 'part_survey') {
1.2 matthew 481: if ($curr_item->{'symb'} eq $target->{'symb'} &&
482: $curr_item->{'part'} eq $target->{'part'}) {
483: last;
484: }
485: } elsif ($granularity eq 'response') {
486: if ($curr_item->{'symb'} eq $target->{'symb'} &&
487: $curr_item->{'part'} eq $target->{'part'} &&
488: $curr_item->{'respid'} eq $target->{'respid'} &&
489: $curr_item->{'resptype'} eq $target->{'resptype'}) {
490: last;
491: }
492: }
493: }
494: my $curr_item = $Resource[$curr_idx];
1.13 matthew 495: if ($granularity eq 'part' || $granularity eq 'part_survey') {
1.2 matthew 496: if ($curr_item->{'symb'} ne $target->{'symb'} ||
497: $curr_item->{'part'} ne $target->{'part'}) {
498: # bogus symb - return nothing
499: return (undef,undef,undef);
500: }
501: } elsif ($granularity eq 'response') {
502: if ($curr_item->{'symb'} ne $target->{'symb'} ||
503: $curr_item->{'part'} ne $target->{'part'} ||
504: $curr_item->{'respid'} ne $target->{'respid'} ||
505: $curr_item->{'resptype'} ne $target->{'resptype'}){
506: # bogus symb - return nothing
507: return (undef,undef,undef);
508: }
509: }
510: #
511: # Now just pick up the data we need
512: my ($prev,$curr,$next);
513: if ($curr_idx == 0) {
514: $prev = undef;
515: $curr = $Resource[$curr_idx ];
516: $next = $Resource[$curr_idx+1];
517: } elsif ($curr_idx == $#Resource) {
518: $prev = $Resource[$curr_idx-1];
519: $curr = $Resource[$curr_idx ];
520: $next = undef;
521: } else {
522: $prev = $Resource[$curr_idx-1];
523: $curr = $Resource[$curr_idx ];
524: $next = $Resource[$curr_idx+1];
525: }
526: return ($prev,$curr,$next);
1.4 matthew 527: }
528:
1.9 matthew 529:
530: #####################################################
531: #####################################################
532:
533: =pod
534:
535: =item GetStudentAnswers($r,$problem,$Students)
536:
537: Determines the correct answer for a set of students on a given problem.
538: The students answers are stored in the student hashes pointed to by the
539: array @$Students under the key 'answer'.
540:
541: Inputs: $r
542: $problem: hash reference containing the keys 'resource', 'part', and 'respid'.
543: $Students: reference to array containing student hashes (need 'username',
544: 'domain').
545:
546: Returns: nothing
547:
548: =cut
549:
550: #####################################################
551: #####################################################
552: sub GetStudentAnswers {
1.12 matthew 553: my ($r,$problem,$Students,$formname,$inputname) = @_;
554: my $status_type;
555: if (defined($formname)) {
556: $status_type = 'inline';
557: } else {
558: $status_type = 'popup';
559: }
1.9 matthew 560: my $c = $r->connection();
561: my %Answers;
562: my ($resource,$partid,$respid) = ($problem->{'resource'},
563: $problem->{'part'},
564: $problem->{'respid'});
565: # Read in the cache (if it exists) before we start timing things.
566: &Apache::lonstathelpers::ensure_proper_cache($resource->{'symb'});
567: # Open progress window
568: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
569: ($r,'Student Answer Compilation Status',
1.12 matthew 570: 'Student Answer Compilation Progress', scalar(@$Students),
571: $status_type,undef,$formname,$inputname);
1.9 matthew 572: $r->rflush();
573: foreach my $student (@$Students) {
574: last if ($c->aborted());
575: my $sname = $student->{'username'};
576: my $sdom = $student->{'domain'};
577: my $answer = &Apache::lonstathelpers::analyze_problem_as_student
578: ($resource,$sname,$sdom,$partid,$respid);
579: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
580: &mt('last student'));
581: $student->{'answer'} = $answer;
582: }
583: &Apache::lonstathelpers::write_answer_cache();
584: return if ($c->aborted());
585: $r->rflush();
586: # close progress window
587: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
588: return;
589: }
1.4 matthew 590:
591: #####################################################
592: #####################################################
593:
594: =pod
595:
596: =item analyze_problem_as_student
597:
598: Analyzes a homework problem for a student and returns the correct answer
599: for the student. Attempts to put together an answer for problem types
600: that do not natively support it.
601:
602: Inputs: $resource: a resource object
603: $sname, $sdom, $partid, $respid
604:
605: Returns: $answer
606:
1.6 matthew 607: If $partid and $respid are specified, $answer is simply a scalar containing
608: the correct answer for the response.
609:
610: If $partid or $respid are undefined, $answer will be a hash reference with
611: keys $partid.'.'.$respid.'.answer'.
612:
1.4 matthew 613: =cut
614:
615: #####################################################
616: #####################################################
617: sub analyze_problem_as_student {
618: my ($resource,$sname,$sdom,$partid,$respid) = @_;
1.22 matthew 619: if (ref($resource) ne 'HASH') {
620: my $res = $resource;
621: $resource = { 'src' => $res->src,
622: 'symb' => $res->symb,
623: 'parts' => $res->parts };
624: foreach my $part (@{$resource->{'parts'}}) {
625: $resource->{'partdata'}->{$part}->{'ResponseIds'}=
626: [$res->responseIds($part)];
627: }
628: }
1.4 matthew 629: my $returnvalue;
630: my $url = $resource->{'src'};
631: my $symb = $resource->{'symb'};
1.8 matthew 632: my $answer = &get_from_answer_cache($sname,$sdom,$symb,$partid,$respid);
633: if (defined($answer)) {
634: return($answer);
635: }
1.4 matthew 636: my $courseid = $ENV{'request.course.id'};
637: my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze',
638: 'grade_domain' => $sdom,
639: 'grade_username' => $sname,
640: 'grade_symb' => $symb,
641: 'grade_courseid' => $courseid));
642: (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
643: my %Answer=&Apache::lonnet::str2hash($Answ);
1.6 matthew 644: #
1.8 matthew 645: undef($answer);
646: foreach my $partid (@{$resource->{'parts'}}) {
1.6 matthew 647: my $partdata = $resource->{'partdata'}->{$partid};
648: foreach my $respid (@{$partdata->{'ResponseIds'}}) {
649: my $prefix = $partid.'.'.$respid;
650: my $key = $prefix.'.answer';
1.8 matthew 651: $answer->{$partid}->{$respid} = &get_answer($prefix,$key,%Answer);
1.6 matthew 652: }
1.8 matthew 653: }
654: &store_answer($sname,$sdom,$symb,undef,undef,$answer);
655: if (! defined($partid)) {
656: $returnvalue = $answer;
657: } elsif (! defined($respid)) {
658: $returnvalue = $answer->{$partid};
1.6 matthew 659: } else {
1.8 matthew 660: $returnvalue = $answer->{$partid}->{$respid};
1.6 matthew 661: }
662: return $returnvalue;
663: }
664:
665: sub get_answer {
666: my ($prefix,$key,%Answer) = @_;
667: my $returnvalue;
1.4 matthew 668: if (exists($Answer{$key})) {
669: my $student_answer = $Answer{$key}->[0];
670: if (! defined($student_answer)) {
671: $student_answer = $Answer{$key}->[1];
672: }
673: $returnvalue = $student_answer;
674: } else {
675: if (exists($Answer{$prefix.'.shown'})) {
676: # The response has foils
677: my %values;
678: while (my ($k,$v) = each(%Answer)) {
679: next if ($k !~ /^$prefix\.foil\.(value|area)\.(.*)$/);
680: my $foilname = $2;
681: $values{$foilname}=$v;
682: }
683: foreach my $foil (@{$Answer{$prefix.'.shown'}}) {
684: if (ref($values{$foil}) eq 'ARRAY') {
1.10 albertel 685: $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
686: join(',',map {&HTML::Entities::encode($_,'<>&"')} @{$values{$foil}}).'&';
1.4 matthew 687: } else {
1.10 albertel 688: $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
689: &HTML::Entities::encode($values{$foil},'<>&"').'&';
1.4 matthew 690: }
691: }
692: $returnvalue =~ s/ /\%20/g;
693: chop ($returnvalue);
694: }
695: }
696: return $returnvalue;
697: }
1.8 matthew 698:
699:
700: #####################################################
701: #####################################################
702:
703: =pod
704:
705: =item Caching routines
706:
707: =over 4
708:
709: =item &load_answer_cache($symb)
710:
711: Loads the cache for the given symb into memory from disk.
712: Requires the cache filename be set.
713: Only should be called by &ensure_proper_cache.
714:
715: =cut
716:
717: #####################################################
718: #####################################################
719: {
720: my $cache_filename = undef;
721: my $current_symb = undef;
722: my %cache;
723:
724: sub load_answer_cache {
725: my ($symb) = @_;
726: return if (! defined($cache_filename));
727: if (! defined($current_symb) || $current_symb ne $symb) {
728: undef(%cache);
729: my $storedstring;
730: my %cache_db;
731: if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_READER(),0640)) {
732: $storedstring = $cache_db{&Apache::lonnet::escape($symb)};
733: untie(%cache_db);
734: }
735: if (defined($storedstring)) {
736: %cache = %{thaw($storedstring)};
737: }
738: }
739: return;
740: }
741:
742: #####################################################
743: #####################################################
744:
745: =pod
746:
747: =item &get_from_answer_cache($sname,$sdom,$symb,$partid,$respid)
748:
749: Returns the appropriate data from the cache, or undef if no data exists.
750: If $respid is undefined, a hash ref containing the answers for the given
751: $partid is returned. If $partid is undefined, a hash ref containing answers
752: for all of the parts is returned.
753:
754: =cut
755:
756: #####################################################
757: #####################################################
758: sub get_from_answer_cache {
759: my ($sname,$sdom,$symb,$partid,$respid) = @_;
760: &ensure_proper_cache($symb);
761: my $returnvalue;
762: if (exists($cache{$sname.':'.$sdom}) &&
763: ref($cache{$sname.':'.$sdom}) eq 'HASH') {
764: if (defined($partid) &&
765: exists($cache{$sname.':'.$sdom}->{$partid})) {
766: if (defined($respid) &&
767: exists($cache{$sname.':'.$sdom}->{$partid}->{$respid})) {
768: $returnvalue = $cache{$sname.':'.$sdom}->{$partid}->{$respid};
769: } else {
770: $returnvalue = $cache{$sname.':'.$sdom}->{$partid};
771: }
772: } else {
773: $returnvalue = $cache{$sname.':'.$sdom};
774: }
775: } else {
776: $returnvalue = undef;
777: }
778: return $returnvalue;
779: }
780:
781: #####################################################
782: #####################################################
783:
784: =pod
785:
786: =item &write_answer_cache($symb)
787:
788: Writes the in memory cache to disk so that it can be read in with
789: &load_answer_cache($symb).
790:
791: =cut
792:
793: #####################################################
794: #####################################################
795: sub write_answer_cache {
796: return if (! defined($current_symb) || ! defined($cache_filename));
797: my %cache_db;
798: my $key = &Apache::lonnet::escape($current_symb);
799: if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_WRCREAT(),0640)) {
800: my $storestring = freeze(\%cache);
801: $cache_db{$key}=$storestring;
802: $cache_db{$key.'.time'}=time;
803: untie(%cache_db);
804: }
805: undef(%cache);
806: undef($current_symb);
807: undef($cache_filename);
808: return;
809: }
810:
811: #####################################################
812: #####################################################
813:
814: =pod
815:
816: =item &ensure_proper_cache($symb)
817:
818: Called to make sure we have the proper cache set up. This is called
819: prior to every answer lookup.
820:
821: =cut
822:
823: #####################################################
824: #####################################################
825: sub ensure_proper_cache {
826: my ($symb) = @_;
827: my $cid = $ENV{'request.course.id'};
828: my $new_filename = '/home/httpd/perl/tmp/'.
1.18 matthew 829: 'problemanalysis_'.$cid.'_answer_cache.db';
1.8 matthew 830: if (! defined($cache_filename) ||
831: $cache_filename ne $new_filename ||
832: ! defined($current_symb) ||
833: $current_symb ne $symb) {
834: $cache_filename = $new_filename;
835: # Notice: $current_symb is not set to $symb until after the cache is
836: # loaded. This is what tells &load_answer_cache to load in a new
837: # symb cache.
838: &load_answer_cache($symb);
839: $current_symb = $symb;
840: }
841: }
842:
843: #####################################################
844: #####################################################
845:
846: =pod
847:
848: =item &store_answer($sname,$sdom,$symb,$partid,$respid,$dataset)
849:
850: Stores the answer data in the in memory cache.
851:
852: =cut
853:
854: #####################################################
855: #####################################################
856: sub store_answer {
857: my ($sname,$sdom,$symb,$partid,$respid,$dataset) = @_;
858: return if ($symb ne $current_symb);
859: if (defined($partid)) {
860: if (defined($respid)) {
861: $cache{$sname.':'.$sdom}->{$partid}->{$respid} = $dataset;
862: } else {
863: $cache{$sname.':'.$sdom}->{$partid} = $dataset;
864: }
865: } else {
866: $cache{$sname.':'.$sdom}=$dataset;
867: }
868: return;
869: }
870:
871: }
872: #####################################################
873: #####################################################
874:
875: =pod
876:
877: =back
878:
879: =cut
880:
881: #####################################################
882: #####################################################
1.4 matthew 883:
884: ##
885: ## The following is copied from datecalc1.pl, part of the
886: ## Spreadsheet::WriteExcel CPAN module.
887: ##
888: ##
889: ######################################################################
890: #
891: # Demonstration of writing date/time cells to Excel spreadsheets,
892: # using UNIX/Perl time as source of date/time.
893: #
894: # Copyright 2000, Andrew Benham, adsb@bigfoot.com
895: #
896: ######################################################################
897: #
898: # UNIX/Perl time is the time since the Epoch (00:00:00 GMT, 1 Jan 1970)
899: # measured in seconds.
900: #
901: # An Excel file can use exactly one of two different date/time systems.
902: # In these systems, a floating point number represents the number of days
903: # (and fractional parts of the day) since a start point. The floating point
904: # number is referred to as a 'serial'.
905: # The two systems ('1900' and '1904') use different starting points:
906: # '1900'; '1.00' is 1 Jan 1900 BUT 1900 is erroneously regarded as
907: # a leap year - see:
908: # http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
909: # for the excuse^H^H^H^H^H^Hreason.
910: # '1904'; '1.00' is 2 Jan 1904.
911: #
912: # The '1904' system is the default for Apple Macs. Windows versions of
913: # Excel have the option to use the '1904' system.
914: #
915: # Note that Visual Basic's "DateSerial" function does NOT erroneously
916: # regard 1900 as a leap year, and thus its serials do not agree with
917: # the 1900 serials of Excel for dates before 1 Mar 1900.
918: #
919: # Note that StarOffice (at least at version 5.2) does NOT erroneously
920: # regard 1900 as a leap year, and thus its serials do not agree with
921: # the 1900 serials of Excel for dates before 1 Mar 1900.
922: #
923: ######################################################################
924: #
925: # Calculation description
926: # =======================
927: #
928: # 1900 system
929: # -----------
930: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 70 years after 1 Jan 1900.
931: # Of those 70 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
932: # were leap years with an extra day.
933: # Thus there were 17 + 70*365 days = 25567 days between 1 Jan 1900 and
934: # 1 Jan 1970.
935: # In the 1900 system, '1' is 1 Jan 1900, but as 1900 was not a leap year
936: # 1 Jan 1900 should really be '2', so 1 Jan 1970 is '25569'.
937: #
938: # 1904 system
939: # -----------
940: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 66 years after 1 Jan 1904.
941: # Of those 66 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
942: # were leap years with an extra day.
943: # Thus there were 17 + 66*365 days = 24107 days between 1 Jan 1904 and
944: # 1 Jan 1970.
945: # In the 1904 system, 2 Jan 1904 being '1', 1 Jan 1970 is '24107'.
946: #
947: ######################################################################
948: #
949: # Copyright (c) 2000, Andrew Benham.
950: # This program is free software. It may be used, redistributed and/or
951: # modified under the same terms as Perl itself.
952: #
953: # Andrew Benham, adsb@bigfoot.com
954: # London, United Kingdom
955: # 11 Nov 2000
956: #
957: ######################################################################
958: #-----------------------------------------------------------
959: # calc_serial()
960: #
961: # Called with (up to) 2 parameters.
962: # 1. Unix timestamp. If omitted, uses current time.
963: # 2. GMT flag. Set to '1' to return serial in GMT.
964: # If omitted, returns serial in appropriate timezone.
965: #
966: # Returns date/time serial according to $DATE_SYSTEM selected
967: #-----------------------------------------------------------
968: sub calc_serial {
969: # Use 1900 date system on all platforms other than Apple Mac (for which
970: # use 1904 date system).
971: my $DATE_SYSTEM = ($^O eq 'MacOS') ? 1 : 0;
972: my $time = (defined $_[0]) ? $_[0] : time();
973: my $gmtflag = (defined $_[1]) ? $_[1] : 0;
974: #
975: # Divide timestamp by number of seconds in a day.
976: # This gives a date serial with '0' on 1 Jan 1970.
977: my $serial = $time / 86400;
978: #
979: # Adjust the date serial by the offset appropriate to the
980: # currently selected system (1900/1904).
981: if ($DATE_SYSTEM == 0) { # use 1900 system
982: $serial += 25569;
983: } else { # use 1904 system
984: $serial += 24107;
985: }
986: #
987: unless ($gmtflag) {
988: # Now have a 'raw' serial with the right offset. But this
989: # gives a serial in GMT, which is false unless the timezone
990: # is GMT. We need to adjust the serial by the appropriate
991: # timezone offset.
992: # Calculate the appropriate timezone offset by seeing what
993: # the differences between localtime and gmtime for the given
994: # time are.
995: #
996: my @gmtime = gmtime($time);
997: my @ltime = localtime($time);
998: #
999: # For the first 7 elements of the two arrays, adjust the
1000: # date serial where the elements differ.
1001: for (0 .. 6) {
1002: my $diff = $ltime[$_] - $gmtime[$_];
1003: if ($diff) {
1004: $serial += _adjustment($diff,$_);
1005: }
1006: }
1007: }
1008: #
1009: # Perpetuate the error that 1900 was a leap year by decrementing
1010: # the serial if we're using the 1900 system and the date is prior to
1011: # 1 Mar 1900. This has the effect of making serial value '60'
1012: # 29 Feb 1900.
1013: #
1014: # This fix only has any effect if UNIX/Perl time on the platform
1015: # can represent 1900. Many can't.
1016: #
1017: unless ($DATE_SYSTEM) {
1018: $serial-- if ($serial < 61); # '61' is 1 Mar 1900
1019: }
1020: return $serial;
1021: }
1022:
1023: sub _adjustment {
1024: # Based on the difference in the localtime/gmtime array elements
1025: # number, return the adjustment required to the serial.
1026: #
1027: # We only look at some elements of the localtime/gmtime arrays:
1028: # seconds unlikely to be different as all known timezones
1029: # have an offset of integral multiples of 15 minutes,
1030: # but it's easy to do.
1031: # minutes will be different for timezone offsets which are
1032: # not an exact number of hours.
1033: # hours very likely to be different.
1034: # weekday will differ when localtime/gmtime difference
1035: # straddles midnight.
1036: #
1037: # Assume that difference between localtime and gmtime is less than
1038: # 5 days, then don't have to do maths for day of month, month number,
1039: # year number, etc...
1040: #
1041: my ($delta,$element) = @_;
1042: my $adjust = 0;
1043: #
1044: if ($element == 0) { # Seconds
1045: $adjust = $delta/86400; # 60 * 60 * 24
1046: } elsif ($element == 1) { # Minutes
1047: $adjust = $delta/1440; # 60 * 24
1048: } elsif ($element == 2) { # Hours
1049: $adjust = $delta/24; # 24
1050: } elsif ($element == 6) { # Day of week number
1051: # Catch difference straddling Sat/Sun in either direction
1052: $delta += 7 if ($delta < -4);
1053: $delta -= 7 if ($delta > 4);
1054: #
1055: $adjust = $delta;
1056: }
1057: return $adjust;
1058: }
1059:
1060: ###########################################################
1061: ###########################################################
1062:
1063: =pod
1064:
1065: =item get_problem_data
1066:
1067: Returns a data structure describing the problem.
1068:
1069: Inputs: $url
1070:
1071: Returns: %Partdata
1072:
1073: =cut
1074:
1075: ## note: we must force each foil and option to not begin or end with
1076: ## spaces as they are stored without such data.
1077: ##
1078: ###########################################################
1079: ###########################################################
1080: sub get_problem_data {
1081: my ($url) = @_;
1082: my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
1083: (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
1084: my %Answer;
1085: %Answer=&Apache::lonnet::str2hash($Answ);
1086: my %Partdata;
1087: foreach my $part (@{$Answer{'parts'}}) {
1088: while (my($key,$value) = each(%Answer)) {
1089: #
1090: # Logging code:
1.7 matthew 1091: if (0) {
1.4 matthew 1092: &Apache::lonnet::logthis($part.' got key "'.$key.'"');
1093: if (ref($value) eq 'ARRAY') {
1094: &Apache::lonnet::logthis(' @'.join(',',@$value));
1095: } else {
1096: &Apache::lonnet::logthis(' '.$value);
1097: }
1098: }
1099: # End of logging code
1100: next if ($key !~ /^$part/);
1101: $key =~ s/^$part\.//;
1102: if (ref($value) eq 'ARRAY') {
1103: if ($key eq 'options') {
1104: $Partdata{$part}->{'_Options'}=$value;
1105: } elsif ($key eq 'concepts') {
1106: $Partdata{$part}->{'_Concepts'}=$value;
1107: } elsif ($key =~ /^concept\.(.*)$/) {
1108: my $concept = $1;
1109: foreach my $foil (@$value) {
1110: $Partdata{$part}->{'_Foils'}->{$foil}->{'_Concept'}=
1111: $concept;
1112: }
1113: } elsif ($key =~ /^(incorrect|answer|ans_low|ans_high)$/) {
1114: $Partdata{$part}->{$key}=$value;
1115: }
1116: } else {
1117: if ($key=~ /^foil\.text\.(.*)$/) {
1118: my $foil = $1;
1119: $Partdata{$part}->{'_Foils'}->{$foil}->{'name'}=$foil;
1120: $value =~ s/(\s*$|^\s*)//g;
1121: $Partdata{$part}->{'_Foils'}->{$foil}->{'text'}=$value;
1122: } elsif ($key =~ /^foil\.value\.(.*)$/) {
1123: my $foil = $1;
1124: $Partdata{$part}->{'_Foils'}->{$foil}->{'value'}=$value;
1125: }
1126: }
1127: }
1128: }
1129: return %Partdata;
1.5 matthew 1130: }
1131:
1132: ####################################################
1133: ####################################################
1134:
1135: =pod
1136:
1137: =item &limit_by_time()
1138:
1139: =cut
1140:
1141: ####################################################
1142: ####################################################
1143: sub limit_by_time_form {
1144: my $Starttime_form = '';
1145: my $starttime = &Apache::lonhtmlcommon::get_date_from_form
1146: ('limitby_startdate');
1147: my $endtime = &Apache::lonhtmlcommon::get_date_from_form
1148: ('limitby_enddate');
1149: if (! defined($endtime)) {
1150: $endtime = time;
1151: }
1152: if (! defined($starttime)) {
1153: $starttime = $endtime - 60*60*24*7;
1154: }
1155: my $state;
1156: if (&limit_by_time()) {
1157: $state = '';
1158: } else {
1159: $state = 'disabled';
1160: }
1161: my $startdateform = &Apache::lonhtmlcommon::date_setter
1162: ('Statistics','limitby_startdate',$starttime,undef,undef,$state);
1163: my $enddateform = &Apache::lonhtmlcommon::date_setter
1164: ('Statistics','limitby_enddate',$endtime,undef,undef,$state);
1165: my $Str;
1166: $Str .= '<script language="Javascript" >';
1167: $Str .= 'function toggle_limitby_activity(state) {';
1168: $Str .= ' if (state) {';
1169: $Str .= ' limitby_startdate_enable();';
1170: $Str .= ' limitby_enddate_enable();';
1171: $Str .= ' } else {';
1172: $Str .= ' limitby_startdate_disable();';
1173: $Str .= ' limitby_enddate_disable();';
1174: $Str .= ' }';
1175: $Str .= '}';
1176: $Str .= '</script>';
1177: $Str .= '<fieldset>';
1178: my $timecheckbox = '<input type="checkbox" name="limit_by_time" ';
1179: if (&limit_by_time()) {
1180: $timecheckbox .= ' checked ';
1181: }
1182: $timecheckbox .= 'OnChange="javascript:toggle_limitby_activity(this.checked);" ';
1183: $timecheckbox .= ' />';
1184: $Str .= '<legend>'.&mt('[_1] Limit by time',$timecheckbox).'</legend>';
1185: $Str .= &mt('Start Time: [_1]',$startdateform).'<br />';
1186: $Str .= &mt(' End Time: [_1]',$enddateform).'<br />';
1187: $Str .= '</fieldset>';
1188: return $Str;
1189: }
1190:
1191: sub limit_by_time {
1192: if (exists($ENV{'form.limit_by_time'}) &&
1193: $ENV{'form.limit_by_time'} ne '' ) {
1194: return 1;
1195: } else {
1196: return 0;
1197: }
1198: }
1199:
1200: sub get_time_limits {
1201: my $starttime = &Apache::lonhtmlcommon::get_date_from_form
1202: ('limitby_startdate');
1203: my $endtime = &Apache::lonhtmlcommon::get_date_from_form
1204: ('limitby_enddate');
1205: return ($starttime,$endtime);
1.11 matthew 1206: }
1207:
1208:
1209:
1210: ####################################################
1211: ####################################################
1212:
1213: =pod
1214:
1215: =item sections_description
1216:
1217: Inputs: @Sections, an array of sections
1218:
1219: Returns: A text description of the sections selected.
1220:
1221: =cut
1222:
1223: ####################################################
1224: ####################################################
1225: sub sections_description {
1226: my @Sections = @_;
1227: my $sectionstring = '';
1228: if (scalar(@Sections) > 1) {
1229: if (scalar(@Sections) > 2) {
1230: my $last = pop(@Sections);
1231: $sectionstring = "Sections ".join(', ',@Sections).', and '.$last;
1232: } else {
1233: $sectionstring = "Sections ".join(' and ',@Sections);
1234: }
1235: } else {
1236: if ($Sections[0] eq 'all') {
1237: $sectionstring = "All sections";
1238: } else {
1239: $sectionstring = "Section ".$Sections[0];
1240: }
1241: }
1242: return $sectionstring;
1.2 matthew 1243: }
1244:
1245: ####################################################
1246: ####################################################
1247:
1248: =pod
1249:
1.12 matthew 1250: =item &manage_caches
1251:
1252: Inputs: $r, apache request object
1253:
1254: Returns: An array of scalars containing html for buttons.
1255:
1256: =cut
1257:
1258: ####################################################
1259: ####################################################
1260: sub manage_caches {
1.23 matthew 1261: my ($r,$formname,$inputname,$update_message) = @_;
1.12 matthew 1262: &Apache::loncoursedata::clear_internal_caches();
1.16 matthew 1263: my $sectionkey =
1264: join(',',
1265: map {
1266: &Apache::lonnet::escape($_);
1267: } sort(@Apache::lonstatistics::SelectedSections)
1268: );
1269: my $statuskey = $Apache::lonstatistics::enrollment_status;
1.12 matthew 1270: if (exists($ENV{'form.ClearCache'}) ||
1.16 matthew 1271: exists($ENV{'form.updatecaches'}) ||
1272: (exists($ENV{'form.firstrun'}) && $ENV{'form.firstrun'} ne 'no') ||
1273: (exists($ENV{'form.prevsection'}) &&
1274: $ENV{'form.prevsection'} ne $sectionkey) ||
1275: (exists($ENV{'form.prevenrollstatus'}) &&
1276: $ENV{'form.prevenrollstatus'} ne $statuskey)
1277: ) {
1.23 matthew 1278: if (defined($update_message)) {
1279: $r->print($update_message);
1280: }
1.12 matthew 1281: &Apache::lonstatistics::Gather_Full_Student_Data($r,$formname,
1282: $inputname);
1.23 matthew 1283:
1.12 matthew 1284: }
1285: #
1.16 matthew 1286: my @Buttons =
1287: ('<input type="submit" name="ClearCache" '.
1288: 'value="'.&mt('Clear Caches').'" />',
1289: '<input type="submit" name="updatecaches" '.
1.17 matthew 1290: 'value="'.&mt('Update Caches').'" />'.
1291: &Apache::loncommon::help_open_topic('Statistics_Cache'),
1.16 matthew 1292: '<input type="hidden" name="prevsection" value="'.$sectionkey.'" />',
1293: '<input type="hidden" name="prevenrollstatus" value="'.$statuskey.'" />'
1294: );
1295: #
1.12 matthew 1296: if (! exists($ENV{'form.firstrun'})) {
1297: $r->print('<input type="hidden" name="firstrun" value="yes" />');
1298: } else {
1299: $r->print('<input type="hidden" name="firstrun" value="no" />');
1300: }
1301: #
1302: return @Buttons;
1303: }
1304:
1305:
1306:
1307:
1308: ####################################################
1309: ####################################################
1310:
1311: =pod
1312:
1.2 matthew 1313: =back
1314:
1315: =cut
1316:
1317: ####################################################
1318: ####################################################
1.1 matthew 1319:
1320: 1;
1321:
1322: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>