1: # The LearningOnline Network with CAPA
2: #
3: # $Id: lonstathelpers.pm,v 1.76.2.3 2020/09/07 02:58:25 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: ####################################################
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();
61: use GDBM_File;
62: use Storable qw(freeze thaw);
63: use lib '/home/httpd/lib/perl/';
64: use LONCAPA;
65:
66:
67: ####################################################
68: ####################################################
69:
70: =pod
71:
72: =item &render_resource($resource)
73:
74: Input: a navmaps resource
75:
76: Retunrs: a scalar containing html for a rendering of the problem
77: within a table.
78:
79: =cut
80:
81: ####################################################
82: ####################################################
83: sub render_resource {
84: my ($resource) = @_;
85: ##
86: ## Render the problem
87: my ($base) = ($resource->src =~ m|^(.*/)[^/]*$|);
88: $base="http://".$ENV{'SERVER_NAME'}.$base;
89: my ($src,$symb)=($resource->link,&escape($resource->shown_symb));
90: my $rendered_problem = &Apache::lonnet::ssi_body($src.'?symb='.$symb);
91: $rendered_problem =~ s/<\s*form\s*/<nop /g;
92: $rendered_problem =~ s|(<\s*/form\s*>)|<\/nop>|g;
93: return '<div class="LC_Box">'.
94: '<h4 class="LC_hcell">'.&mt('Problem').'</h4>'.
95: '<base href="'.$base.'" />'.$rendered_problem.
96: '</div>';
97: }
98:
99: ####################################################
100: ####################################################
101:
102: =pod
103:
104: =item &get_resources
105:
106: =cut
107:
108: ####################################################
109: ####################################################
110: sub get_resources {
111: my ($navmap,$sequence) = @_;
112: my @resources = $navmap->retrieveResources($sequence,
113: sub { shift->is_problem(); },
114: 0,0,0);
115: return @resources;
116: }
117:
118: ####################################################
119: ####################################################
120:
121: =pod
122:
123: =item &problem_selector($AcceptedResponseTypes)
124:
125: Input: scalar containing regular expression which matches response
126: types to show. '.' will yield all, '(option|radiobutton)' will match
127: all option response and radiobutton problems.
128:
129: Returns: A string containing html for a table which lists the sequences
130: and their contents. A radiobutton is provided for each problem.
131: Skips 'survey' problems.
132:
133: =cut
134:
135: ####################################################
136: ####################################################
137: sub problem_selector {
138: my ($AcceptedResponseTypes,$sequence_addendum,$symbmode,$all,$prefix,
139: $byres,$include_tools,$smallbox,$onclick) = @_;
140: # all: also make sequences selectable
141: # prefix: prefix for all form names
142: # byres: radiobutton shown per resource
143: # include_tools: external tools included
144: # smallbox: use smaller box
145: # onclick: javascript to execute when clicked
146: my $Str;
147: my $jsadd='';
148: if ($onclick) {
149: $jsadd="onclick='$onclick'";
150: }
151: $Str = &Apache::loncommon::start_scrollbox(($smallbox?'420px':'620px'),
152: ($smallbox?'400px':'600px'),
153: ($smallbox?'60px':'300px')).
154: &Apache::loncommon::start_data_table();
155: my $rb_count =0;
156: my ($navmap,@sequences) =
157: &Apache::lonstatistics::selected_sequences_with_assessments('all');
158: return $navmap if (! ref($navmap)); # error
159: foreach my $seq (@sequences) {
160: my $seq_str = '';
161: foreach my $res (&get_resources($navmap,$seq)) {
162: if ($res->src() eq '/res/lib/templates/simpleproblem.problem') {
163: next if (grep(/^placeholder$/,@{$res->parts}));
164: }
165: my $title = $res->compTitle;
166: if (! defined($title) || $title eq '') {
167: ($title) = ($res->src =~ m:/([^/]*)$:);
168: }
169: my $totalresps = 0;
170: if ($byres) {
171: foreach my $part (@{$res->parts}) {
172: $totalresps += scalar($res->responseIds($part));
173: }
174: my $value = &HTML::Entities::encode($res->symb(),'<>&"');
175: my $checked;
176: if ($env{'form.problemchoice'} eq $res->symb()) {
177: $checked = ' checked="checked"';
178: }
179: my $rowspan;
180: if ($totalresps > 1) {
181: $rowspan = ' rowspan="'.$totalresps.'"';
182: }
183: $seq_str .= &Apache::loncommon::start_data_table_row().
184: '<td'.$rowspan.' style="vertical-align:top">'.
185: '<label><input type="radio" name="symb" value="'.$value.'"'.$checked.' />'.
186: $title.'</label>';
187: my $link = $res->link.'?symb='.&escape($res->shown_symb);
188: $seq_str .= (' 'x2).
189: '<a target="preview" href="'.$link.'">'.&mt('view').'</a></td>';
190: }
191: my %partsseen;
192: foreach my $part (@{$res->parts}) {
193: my @response_ids = $res->responseIds($part);
194: my @response_types = $res->responseType($part);
195: for (my $i=0;$i<scalar(@response_types);$i++){
196: my $respid = $response_ids[$i];
197: my $resptype = $response_types[$i];
198: if ($resptype =~ m/$AcceptedResponseTypes/) {
199: if ($byres) {
200: if (exists($partsseen{$part})) {
201: $seq_str .= &Apache::loncommon::continue_data_table_row();
202: } else {
203: my $parttitle = $part;
204: if ($part eq '0') {
205: $parttitle = '';
206: }
207: if ($parttitle ne '') {
208: $parttitle = (' 'x2).&mt('part').': '.$parttitle;
209: }
210: if (keys(%partsseen)) {
211: $seq_str .= &Apache::loncommon::continue_data_table_row();
212: }
213: unless ($partsseen{$part}) {
214: my $resprowspan;
215: if (scalar(@response_ids) > 1) {
216: $resprowspan = ' rowspan="'.scalar(@response_ids).'"';
217: }
218: $seq_str .= '<td'.$resprowspan.' style="vertical-align:top">'.
219: $parttitle.'</td>';
220: $partsseen{$part} = scalar(@response_ids);
221: }
222: }
223: $seq_str .= '<td>'.$resptype;
224: if (scalar(@response_ids) > 1) {
225: $seq_str .= ' '.&mt('id').': '.$respid;
226: }
227: $seq_str .= '</td>'. &Apache::loncommon::end_data_table_row()."\n";
228: } else {
229: my $value = &make_target_id({symb=>$res->symb,
230: part=>$part,
231: respid=>$respid,
232: resptype=>$resptype});
233: my $checked = '';
234: if ($env{'form.problemchoice'} eq $value) {
235: $checked = ' checked="checked"';
236: }
237: $seq_str .= &Apache::loncommon::start_data_table_row().
238: ($symbmode?
239: '<td><input type="radio" id="'.$prefix.$rb_count.'" name="'.$prefix.'symb" value="'.&HTML::Entities::encode($res->symb,'<>&"').'" '.$checked.' '.
240: $jsadd.
241: ' /></td>'
242: :qq{<td><input type="radio" id="$rb_count" name="problemchoice" value="$value"$checked /></td>}).
243: '<td><label for="'.$prefix.$rb_count.'">'.$resptype.'</label></td>'.
244: '<td><label for="'.$prefix.$rb_count.'">'.$title.'</label>';
245: if (scalar(@response_ids) > 1) {
246: $seq_str .= &mt('response').' '.$respid;
247: }
248: my $link = $res->link.'?symb='.&escape($res->shown_symb);
249: $seq_str .= (' 'x2).
250: '<a target="preview" href="'.$link.'">'.&mt('view').'</a>';
251: $seq_str .= "</td>". &Apache::loncommon::end_data_table_row()."\n";
252: $rb_count++;
253: }
254: }
255: }
256: }
257: }
258: if ($seq_str ne '') {
259: if ($byres) {
260: $Str .= &Apache::loncommon::start_data_table_header_row().
261: '<th colspan="3">'.$seq->compTitle.'</th>'.
262: &Apache::loncommon::end_data_table_header_row().
263: $seq_str;
264: } else {
265: $Str .= &Apache::loncommon::start_data_table_header_row().
266: '<th colspan="3">'.
267: ($all?'<input type="radio" id="'.$prefix.'s'.$rb_count.'" name="'.$prefix.'symb" value="'.&HTML::Entities::encode($seq->symb,'<>&').'" '.$jsadd.' />':'').
268: $seq->compTitle.'</th>'.
269: &Apache::loncommon::end_data_table_header_row()."\n".$seq_str;
270: if (defined($sequence_addendum)) {
271: $Str .= &Apache::loncommon::start_data_table_header_row().
272: ('<td> </td>'x2).
273: '<td align="right">'.$sequence_addendum.'</td>'.
274: &Apache::loncommon::end_data_table_header_row()."\n";
275: }
276: }
277: }
278: }
279: $Str .= &Apache::loncommon::end_data_table().&Apache::loncommon::end_scrollbox()."\n";
280: return $Str;
281: }
282:
283: ####################################################
284: ####################################################
285:
286: =pod
287:
288: =item &MultipleProblemSelector($navmap,$selected,$inputname)
289:
290: Generate HTML with checkboxes for problem selection.
291:
292: Input:
293:
294: $navmap: a navmap object. If undef, navmaps will be called to create a
295: new object.
296:
297: $selected: Scalar, Array, or hash reference of currently selected items.
298:
299: $inputname: The name of the form elements to use for the checkboxs.
300:
301: Returns: A string containing html for a table which lists the sequences
302: and their contents. A checkbox is provided for each problem.
303:
304: =cut
305:
306: ####################################################
307: ####################################################
308: sub MultipleProblemSelector {
309: my ($navmap,$inputname,$formname,$anoncounter)=@_;
310: my $cid = $env{'request.course.id'};
311: my $Str;
312: # Massage the input as needed.
313: if (! defined($navmap)) {
314: $navmap = Apache::lonnavmaps::navmap->new();
315: if (! defined($navmap)) {
316: $Str .= '<div class="LC_error">'
317: .&mt('Error: cannot process course structure')
318: .'</div>';
319: return $Str;
320: }
321: }
322: my $selected = {map { ($_,1) } (&get_selected_symbs($inputname))};
323: # Header
324: $Str .= <<"END";
325: <script type="text/javascript" language="JavaScript">
326: function checkall(value,seqid) {
327: for (i=0; i<document.forms.$formname.elements.length; i++) {
328: ele = document.forms.$formname.elements[i];
329: if (ele.name == '$inputname') {
330: if (seqid != null) {
331: itemid = document.forms.$formname.elements[i].id;
332: thing = itemid.split(':');
333: if (thing[0] == seqid) {
334: document.forms.$formname.elements[i].checked=value;
335: }
336: } else {
337: document.forms.$formname.elements[i].checked=value;
338: }
339: }
340: }
341: }
342: </script>
343: END
344: my $checkanonjs = <<"END";
345:
346: <script type="text/javascript" language="JavaScript">
347: function checkanon() {
348: return true;
349: }
350: </script>
351:
352: END
353: if (ref($anoncounter) eq 'HASH') {
354: if (keys(%{$anoncounter}) > 0) {
355: my $anonwarning = &mt('Your selection includes both problems with and without anonymous submissions.')."\n".&mt('You must select either only anonymous or only named problems.')."\n\n".&mt('If a selection contains both anonymous and named parts,[_1]use the Anonymous/Named buttons to ensure selections will be either all anonymous[_1]or all named.',"\n");
356: &js_escape(\$anonwarning);
357: $checkanonjs = <<"END";
358:
359: <script type="text/javascript" language="JavaScript">
360: function checkanon() {
361: anoncount = 0;
362: namedcount = 0;
363: for (i=0; i<document.forms.$formname.elements.length; i++) {
364: ele = document.forms.$formname.elements[i];
365: if (ele.name == '$inputname') {
366: itemid = document.forms.$formname.elements[i].id;
367: if (document.forms.$formname.elements[i].checked) {
368: anonid = 'anonymous_'+itemid;
369: mixid = 'mixed_'+itemid;
370: anonele = document.getElementById(anonid);
371: mixele = document.getElementById(mixid);
372: if (anonele.value > 0) {
373: if (mixele.value == 'none') {
374: anoncount ++;
375: } else {
376: if (mixele.value == '0') {
377: if (mixele.checked) {
378: anoncount ++;
379: } else {
380: namedcount ++;
381: }
382: } else {
383: namedcount ++;
384: }
385: }
386: } else {
387: namedcount ++;
388: }
389: }
390: }
391: }
392: if (anoncount > 0 && namedcount > 0) {
393: alert("$anonwarning");
394: return false;
395: }
396: }
397: </script>
398:
399: END
400: }
401: }
402: $Str .= $checkanonjs.
403: '<a href="javascript:checkall(true)">'.&mt('Select All').'</a>'.
404: (' 'x4).
405: '<a href="javascript:checkall(false)">'.&mt('Unselect All').'</a>';
406: $Str .= $/.'<table>'.$/;
407: my $iterator = $navmap->getIterator(undef, undef, undef, 1);
408: my $sequence_string;
409: my $seq_id = 0;
410: my @Accumulator = (&new_accumulator($env{'course.'.$cid.'.description'},
411: '',
412: '',
413: $seq_id++,
414: $inputname));
415: my @Sequence_Data;
416: while (my $curRes = $iterator->next()) {
417: if ($curRes == $iterator->END_MAP) {
418: if (ref($Accumulator[-1]) eq 'CODE') {
419: my $old_accumulator = pop(@Accumulator);
420: push(@Sequence_Data,&{$old_accumulator}());
421: }
422: } elsif ($curRes == $iterator->BEGIN_MAP) {
423: # Not much to do here.
424: }
425: next if (! ref($curRes));
426: if ($curRes->is_map) {
427: push(@Accumulator,&new_accumulator($curRes->compTitle,
428: $curRes->src,
429: $curRes->symb,
430: $seq_id++,
431: $inputname));
432: } elsif ($curRes->is_problem) {
433: my $anonpart = 0;
434: my $namedpart = 0;
435: my @parts = @{$curRes->parts()};
436: if (ref($anoncounter) eq 'HASH') {
437: if (keys(%{$anoncounter}) > 0) {
438: my @parts = @{$curRes->parts()};
439: my $symb = $curRes->symb();
440: foreach my $part (@parts) {
441: if ((exists($anoncounter->{$symb."\0".$part})) ||
442: $curRes->is_anonsurvey($part)) {
443: $anonpart ++;
444: } else {
445: $namedpart ++
446: }
447: }
448: }
449: }
450: if (@Accumulator && $Accumulator[-1] ne '') {
451: &{$Accumulator[-1]}($curRes,
452: exists($selected->{$curRes->symb}),
453: $anonpart,$namedpart);
454: }
455: }
456: }
457: my $course_seq = pop(@Sequence_Data);
458: foreach my $seq ($course_seq,@Sequence_Data) {
459: #my $seq = pop(@Sequence_Data);
460: next if (! defined($seq) || ref($seq) ne 'HASH');
461: $Str.= '<tr><td colspan="2">'.
462: '<b>'.$seq->{'title'}.'</b>'.(' 'x2).
463: '<a href="javascript:checkall(true,'.$seq->{'id'}.')">'.
464: &mt('Select').'</a>'.(' 'x2).
465: '<a href="javascript:checkall(false,'.$seq->{'id'}.')">'.
466: &mt('Unselect').'</a>'.(' 'x2).
467: '</td></tr>'.$/;
468: $Str.= $seq->{'html'};
469: }
470: $Str .= '</table>'.$/;
471: return $Str;
472: }
473:
474: sub new_accumulator {
475: my ($title,$src,$symb,$seq_id,$inputname) = @_;
476: my $target;
477: my $item_id=0;
478: return
479: sub {
480: if (@_) {
481: my ($res,$checked,$anonpart,$namedpart) = @_;
482: $target.='<tr><td><label>'.
483: '<input type="checkbox" name="'.$inputname.'" ';
484: if ($checked) {
485: $target .= 'checked="checked" ';
486: }
487: my $anon_id = $item_id;
488: $target .= 'id="'.$seq_id.':'.$item_id++.'" ';
489: my $esc_symb = &escape($res->symb);
490: $target.=
491: 'value="'.$esc_symb.'" />'.
492: ' '.$res->compTitle.'</label>'.
493: (' 'x2).'<a target="preview" '.
494: 'href="'.$res->link.'?symb='.
495: &escape($res->shown_symb).'">'.&mt('view').'</a>'.
496: '<input type="hidden" id="anonymous_'.$seq_id.':'.$anon_id.'" name="hidden_'.$seq_id.':'.$anon_id.'" value="'.$anonpart.'" />';
497: my $mixed = '<input type="hidden" id="mixed_'.$seq_id.':'.$anon_id.'" value="none" name="mixed_'.$seq_id.':'.$anon_id.'" />';
498: if ($anonpart) {
499: if ($namedpart) {
500: my $checknamed = '';
501: my $checkedanon = ' checked="checked"';
502: if ($env{'form.mixed_'.$seq_id.':'.$anon_id} eq $esc_symb) {
503: $checknamed = $checkedanon;
504: $checkedanon = '';
505: }
506: $mixed = ' ('.
507: &mt('Both anonymous and named submissions -- display: [_1]Anonymous [_2]Named[_3]',
508: '<span class="LC_nobreak"><label>'.
509: '<input type="radio" name="mixed_'.$seq_id.':'.$anon_id.
510: '" value="0" id="mixed_'.$seq_id.':'.$anon_id.'"'.$checkedanon.' />',
511: '</label></span>'.(' 'x2).' <span class="LC_nobreak">'.
512: '<label><input type="radio" name="mixed_'.$seq_id.':'.$anon_id.
513: '" value="symb_'.$esc_symb.'" id="named_'.$seq_id.':'.$anon_id.'"'.$checknamed.' />',
514: '</label></span>').')';
515: } else {
516: $target .= ' '.&mt('(Anonymous Survey)');
517: }
518: }
519: $target.= $mixed.'</td></tr>'.$/;
520: } else {
521: if (defined($target)) {
522: return { title => $title,
523: symb => $symb,
524: src => $src,
525: id => $seq_id,
526: html => $target, };
527: }
528: return undef;
529: }
530: };
531: }
532:
533: sub get_selected_symbs {
534: my ($inputfield) = @_;
535: my $field = 'form.'.$inputfield;
536: my @symbs = (map {
537: &unescape($_);
538: } &Apache::loncommon::get_env_multiple($field));
539: return @symbs;
540: }
541:
542: ####################################################
543: ####################################################
544:
545: =pod
546:
547: =item &make_target_id($target)
548:
549: Inputs: Hash ref with the following entries:
550: $target->{'symb'}, $target->{'part'}, $target->{'respid'},
551: $target->{'resptype'}.
552:
553: Returns: A string, suitable for a form parameter, which uniquely identifies
554: the problem, part, and response to do statistical analysis on.
555:
556: Used by Apache::lonstathelpers::ProblemSelector().
557:
558: =cut
559:
560: ####################################################
561: ####################################################
562: sub make_target_id {
563: my ($target) = @_;
564: my $id = &escape($target->{'symb'}).':'.
565: &escape($target->{'part'}).':'.
566: &escape($target->{'respid'}).':'.
567: &escape($target->{'resptype'});
568: return $id;
569: }
570:
571: ####################################################
572: ####################################################
573:
574: =pod
575:
576: =item &get_target_from_id($id)
577:
578: Inputs: $id, a scalar string from Apache::lonstathelpers::make_target_id().
579:
580: Returns: A hash reference, $target, containing the following keys:
581: $target->{'symb'}, $target->{'part'}, $target->{'respid'},
582: $target->{'resptype'}.
583:
584: =cut
585:
586: ####################################################
587: ####################################################
588: sub get_target_from_id {
589: my ($id) = @_;
590: if (! ref($id)) {
591: my ($symb,$part,$respid,$resptype) = split(':',$id);
592: return ({ symb => &unescape($symb),
593: part => &unescape($part),
594: respid => &unescape($respid),
595: resptype => &unescape($resptype)});
596: } elsif (ref($id) eq 'ARRAY') {
597: my @Return;
598: foreach my $selected (@$id) {
599: my ($symb,$part,$respid,$resptype) = split(':',$selected);
600: push(@Return,{ symb => &unescape($symb),
601: part => &unescape($part),
602: respid => &unescape($respid),
603: resptype => &unescape($resptype)});
604: }
605: return \@Return;
606: }
607: }
608:
609: ####################################################
610: ####################################################
611:
612: =pod
613:
614: =item &get_prev_curr_next($target,$AcceptableResponseTypes,$granularity)
615:
616: Determine the problem parts or responses preceeding and following the
617: current resource.
618:
619: Inputs: $target (see &Apache::lonstathelpers::get_target_from_id())
620: $AcceptableResponseTypes, regular expression matching acceptable
621: response types,
622: $granularity, either 'part', 'response', 'part_survey', or 'part_task'
623:
624: Returns: three hash references, $prev, $curr, $next, which refer to the
625: preceeding, current, or following problem parts or responses, depending
626: on the value of $granularity. Values of undef indicate there is no
627: previous or next part/response. A value of undef for all three indicates
628: there was no match found to the current part/resource.
629:
630: The hash references contain the following keys:
631: symb, part, resource
632:
633: If $granularity eq 'response', the following ADDITIONAL keys will be present:
634: respid, resptype
635:
636: =cut
637:
638: ####################################################
639: ####################################################
640: sub get_prev_curr_next {
641: my ($target,$AcceptableResponseTypes,$granularity) = @_;
642: #
643: # Build an array with the data we need to search through
644: my @Resource;
645: my ($navmap,@sequences) =
646: &Apache::lonstatistics::selected_sequences_with_assessments('all');
647: return $navmap if (! ref($navmap));
648: foreach my $seq (@sequences) {
649: my @resources = &get_resources($navmap,$seq);
650: foreach my $res (@resources) {
651: foreach my $part (@{$res->parts}) {
652: if (($res->is_survey($part) || ($res->is_anonsurvey($part))) &&
653: ($granularity eq 'part_survey')) {
654: push (@Resource,
655: { symb => $res->symb,
656: part => $part,
657: resource => $res,
658: } );
659: } elsif ($res->is_task($part) && ($granularity eq 'part_task')){
660: push (@Resource,
661: { symb => $res->symb,
662: part => $part,
663: resource => $res,
664: } );
665: } elsif ($granularity eq 'part') {
666: push (@Resource,
667: { symb => $res->symb,
668: part => $part,
669: resource => $res,
670: } );
671: } elsif ($granularity eq 'response') {
672: my @response_ids = $res->responseIds($part);
673: my @response_types = $res->responseType($part);
674: for (my $i=0;
675: $i<scalar(@response_ids);
676: $i++){
677: my $respid = $response_ids[$i];
678: my $resptype = $response_types[$i];
679: next if ($resptype !~ m/$AcceptableResponseTypes/);
680: push (@Resource,
681: { symb => $res->symb,
682: part => $part,
683: respid => $respid,
684: resptype => $resptype,
685: resource => $res,
686: } );
687: }
688: }
689: }
690: }
691: }
692: #
693: # Get the index of the current situation
694: my $curr_idx;
695: for ($curr_idx=0;$curr_idx<$#Resource;$curr_idx++) {
696: my $curr_item = $Resource[$curr_idx];
697: if ($granularity =~ /^(part|part_survey|part_task)$/) {
698: if ($curr_item->{'symb'} eq $target->{'symb'} &&
699: $curr_item->{'part'} eq $target->{'part'}) {
700: last;
701: }
702: } elsif ($granularity eq 'response') {
703: if ($curr_item->{'symb'} eq $target->{'symb'} &&
704: $curr_item->{'part'} eq $target->{'part'} &&
705: $curr_item->{'respid'} eq $target->{'respid'} &&
706: $curr_item->{'resptype'} eq $target->{'resptype'}) {
707: last;
708: }
709: }
710: }
711: my $curr_item = $Resource[$curr_idx];
712: if ($granularity =~ /^(part|part_survey|part_task)$/) {
713: if ($curr_item->{'symb'} ne $target->{'symb'} ||
714: $curr_item->{'part'} ne $target->{'part'}) {
715: # bogus symb - return nothing
716: return (undef,undef,undef);
717: }
718: } elsif ($granularity eq 'response') {
719: if ($curr_item->{'symb'} ne $target->{'symb'} ||
720: $curr_item->{'part'} ne $target->{'part'} ||
721: $curr_item->{'respid'} ne $target->{'respid'} ||
722: $curr_item->{'resptype'} ne $target->{'resptype'}){
723: # bogus symb - return nothing
724: return (undef,undef,undef);
725: }
726: }
727: #
728: # Now just pick up the data we need
729: my ($prev,$curr,$next);
730: if ($curr_idx == 0) {
731: $prev = undef;
732: $curr = $Resource[$curr_idx ];
733: $next = $Resource[$curr_idx+1];
734: } elsif ($curr_idx == $#Resource) {
735: $prev = $Resource[$curr_idx-1];
736: $curr = $Resource[$curr_idx ];
737: $next = undef;
738: } else {
739: $prev = $Resource[$curr_idx-1];
740: $curr = $Resource[$curr_idx ];
741: $next = $Resource[$curr_idx+1];
742: }
743: return ($navmap,$prev,$curr,$next);
744: }
745:
746:
747: #####################################################
748: #####################################################
749:
750: =pod
751:
752: =item GetStudentAnswers($r,$problem,$Students)
753:
754: Determines the correct answer for a set of students on a given problem.
755: The students answers are stored in the student hashes pointed to by the
756: array @$Students under the key 'answer'.
757:
758: Inputs: $r
759: $problem: hash reference containing the keys 'resource', 'part', and 'respid'.
760: $Students: reference to array containing student hashes (need 'username',
761: 'domain').
762:
763: Returns: nothing
764:
765: =cut
766:
767: #####################################################
768: #####################################################
769: sub GetStudentAnswers {
770: my ($r,$problem,$Students,$formname,$inputname) = @_;
771: my %answers;
772: my $status_type;
773: if (defined($formname)) {
774: $status_type = 'inline';
775: } else {
776: $status_type = 'popup';
777: }
778: my $c = $r->connection();
779: my %Answers;
780: my ($resource,$partid,$respid) = ($problem->{'resource'},
781: $problem->{'part'},
782: $problem->{'respid'});
783: # Read in the cache (if it exists) before we start timing things.
784: &Apache::lonstathelpers::ensure_proper_cache($resource->{'symb'});
785: # Open progress window
786: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,scalar(@$Students));
787: $r->rflush();
788: foreach my $student (@$Students) {
789: last if ($c->aborted());
790: my $sname = $student->{'username'};
791: my $sdom = $student->{'domain'};
792: my $answer = &Apache::lonstathelpers::get_student_answer
793: ($resource,$sname,$sdom,$partid,$respid);
794: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
795: 'last student');
796: $answers{$answer}++;
797: $student->{'answer'} = $answer;
798: }
799: &Apache::lonstathelpers::write_analysis_cache();
800: return if ($c->aborted());
801: $r->rflush();
802: # close progress window
803: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
804: return \%answers;
805: }
806:
807: #####################################################
808: #####################################################
809:
810: =pod
811:
812: =item analyze_problem_as_student
813:
814: Analyzes a homework problem for a student
815:
816: Inputs: $resource: a resource object
817: $sname, $sdom, $partid, $respid
818:
819: Returns: the problem analysis hash
820:
821: =cut
822:
823: #####################################################
824: #####################################################
825: sub analyze_problem_as_student {
826: my ($resource,$sname,$sdom) = @_;
827: if (ref($resource) ne 'HASH') {
828: my $res = $resource;
829: $resource = { 'src' => $res->src,
830: 'symb' => $res->symb,
831: 'parts' => $res->parts };
832: foreach my $part (@{$resource->{'parts'}}) {
833: $resource->{'partdata'}->{$part}->{'ResponseIds'}=
834: [$res->responseIds($part)];
835: }
836: }
837: my $url = $resource->{'src'};
838: my $symb = $resource->{'symb'};
839: my $analysis = &get_from_analysis_cache($sname,$sdom,$symb);
840: if (! defined($analysis)) {
841: my $courseid = $env{'request.course.id'};
842: my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze',
843: 'grade_domain' => $sdom,
844: 'grade_username' => $sname,
845: 'grade_symb' => $symb,
846: 'grade_courseid' => $courseid));
847: (my $garbage,$analysis)=split(/_HASH_REF__/,$Answ,2);
848: &store_analysis($sname,$sdom,$symb,$analysis);
849: }
850: my %Answer=&Apache::lonnet::str2hash($analysis);
851: #
852: return \%Answer;
853: }
854:
855: #####################################################
856: #####################################################
857:
858: =pod
859:
860: =item get_student_answer
861:
862: Analyzes a homework problem for a particular student and returns the correct
863: answer. Attempts to put together an answer for problem types
864: that do not natively support it.
865:
866: Inputs: $resource: a resource object (from navmaps or hash from loncoursedata)
867: $sname, $sdom, $partid, $respid
868:
869: Returns: $answer
870:
871: If $partid and $respid are specified, $answer is simply a scalar containing
872: the correct answer for the response.
873:
874: If $partid or $respid are undefined, $answer will be a hash reference with
875: keys $partid.'.'.$respid.'.answer'.
876:
877: =cut
878:
879: #####################################################
880: #####################################################
881: sub get_student_answer {
882: my ($resource,$sname,$sdom,$partid,$respid) = @_;
883: #
884: if (ref($resource) ne 'HASH') {
885: my $res = $resource;
886: $resource = { 'src' => $res->src,
887: 'symb' => $res->symb,
888: 'parts' => $res->parts };
889: foreach my $part (@{$resource->{'parts'}}) {
890: $resource->{'partdata'}->{$part}->{'ResponseIds'}=
891: [$res->responseIds($part)];
892: }
893: }
894: #
895: my $analysis =
896: &analyze_problem_as_student($resource,$sname,$sdom);
897: my $answer;
898: foreach my $partid (@{$resource->{'parts'}}) {
899: my $partdata = $resource->{'partdata'}->{$partid};
900: foreach my $respid (@{$partdata->{'ResponseIds'}}) {
901: my $prefix = $partid.'.'.$respid;
902: my $key = $prefix.'.answer';
903: $answer->{$partid}->{$respid} =
904: &get_answer($prefix,$key,%$analysis);
905: }
906: }
907: my $returnvalue;
908: if (! defined($partid)) {
909: $returnvalue = $answer;
910: } elsif (! defined($respid)) {
911: $returnvalue = $answer->{$partid};
912: } else {
913: $returnvalue = $answer->{$partid}->{$respid};
914: }
915: return $returnvalue;
916: }
917:
918: sub get_answer {
919: my ($prefix,$key,%Answer) = @_;
920: my $returnvalue;
921: if (exists($Answer{$key})) {
922: if (ref($Answer{$key}) eq 'HASH') {
923: my $which = 'INTERNAL';
924: if (!exists($Answer{$key}{$which})) {
925: $which = (sort(keys(%{ $Answer{$key} })))[0];
926: }
927: my $student_answer = $Answer{$key}{$which}[0][0];
928: $returnvalue = $student_answer;
929: } else {
930: &Apache::lonnet::logthis("error analyzing problem. got a answer of type ".ref($Answer{$key}));
931: }
932: } else {
933: if (exists($Answer{$prefix.'.shown'})) {
934: # The response has foils
935: my %values;
936: while (my ($k,$v) = each(%Answer)) {
937: next if ($k !~ /^$prefix\.foil\.(value|area)\.(.*)$/);
938: my $foilname = $2;
939: $values{$foilname}=$v;
940: }
941: foreach my $foil (@{$Answer{$prefix.'.shown'}}) {
942: if (ref($values{$foil}) eq 'ARRAY') {
943: $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
944: join(',',map {&HTML::Entities::encode($_,'<>&"')} @{$values{$foil}}).'&';
945: } else {
946: $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
947: &HTML::Entities::encode($values{$foil},'<>&"').'&';
948: }
949: }
950: $returnvalue =~ s/ /\%20/g;
951: chop ($returnvalue);
952: }
953: }
954: return $returnvalue;
955: }
956:
957: #####################################################
958: #####################################################
959:
960: =pod
961:
962: =item Caching routines
963:
964: =over 4
965:
966: =item &load_analysis_cache($symb)
967:
968: Loads the cache for the given symb into memory from disk.
969: Requires the cache filename be set.
970: Only should be called by &ensure_proper_cache.
971:
972: =cut
973:
974: #####################################################
975: #####################################################
976: {
977: my $cache_filename = undef;
978: my $current_symb = undef;
979: my %cache;
980:
981: sub load_analysis_cache {
982: my ($symb) = @_;
983: return if (! defined($cache_filename));
984: if (! defined($current_symb) || $current_symb ne $symb) {
985: undef(%cache);
986: my $storedstring;
987: my %cache_db;
988: if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_READER(),0640)) {
989: $storedstring = $cache_db{&escape($symb)};
990: untie(%cache_db);
991: }
992: if (defined($storedstring)) {
993: %cache = %{thaw($storedstring)};
994: }
995: }
996: return;
997: }
998:
999: #####################################################
1000: #####################################################
1001:
1002: =pod
1003:
1004: =item &get_from_analysis_cache($sname,$sdom,$symb,$partid,$respid)
1005:
1006: Returns the appropriate data from the cache, or undef if no data exists.
1007:
1008: =cut
1009:
1010: #####################################################
1011: #####################################################
1012: sub get_from_analysis_cache {
1013: my ($sname,$sdom,$symb) = @_;
1014: &ensure_proper_cache($symb);
1015: my $returnvalue;
1016: if (exists($cache{$sname.':'.$sdom})) {
1017: $returnvalue = $cache{$sname.':'.$sdom};
1018: } else {
1019: $returnvalue = undef;
1020: }
1021: return $returnvalue;
1022: }
1023:
1024: #####################################################
1025: #####################################################
1026:
1027: =pod
1028:
1029: =item &write_analysis_cache($symb)
1030:
1031: Writes the in memory cache to disk so that it can be read in with
1032: &load_analysis_cache($symb).
1033:
1034: =cut
1035:
1036: #####################################################
1037: #####################################################
1038: sub write_analysis_cache {
1039: return if (! defined($current_symb) || ! defined($cache_filename));
1040: my %cache_db;
1041: my $key = &escape($current_symb);
1042: if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_WRCREAT(),0640)) {
1043: my $storestring = freeze(\%cache);
1044: $cache_db{$key}=$storestring;
1045: $cache_db{$key.'.time'}=time;
1046: untie(%cache_db);
1047: }
1048: undef(%cache);
1049: undef($current_symb);
1050: undef($cache_filename);
1051: return;
1052: }
1053:
1054: #####################################################
1055: #####################################################
1056:
1057: =pod
1058:
1059: =item &ensure_proper_cache($symb)
1060:
1061: Called to make sure we have the proper cache set up. This is called
1062: prior to every analysis lookup.
1063:
1064: =cut
1065:
1066: #####################################################
1067: #####################################################
1068: sub ensure_proper_cache {
1069: my ($symb) = @_;
1070: my $cid = $env{'request.course.id'};
1071: my $new_filename = LONCAPA::tempdir() .
1072: 'problemanalysis_'.$cid.'_analysis_cache.db';
1073: if (! defined($cache_filename) ||
1074: $cache_filename ne $new_filename ||
1075: ! defined($current_symb) ||
1076: $current_symb ne $symb) {
1077: $cache_filename = $new_filename;
1078: # Notice: $current_symb is not set to $symb until after the cache is
1079: # loaded. This is what tells &load_analysis_cache to load in a new
1080: # symb cache.
1081: &load_analysis_cache($symb);
1082: $current_symb = $symb;
1083: }
1084: }
1085:
1086: #####################################################
1087: #####################################################
1088:
1089: =pod
1090:
1091: =item &store_analysis($sname,$sdom,$symb,$partid,$respid,$dataset)
1092:
1093: Stores the analysis data in the in memory cache.
1094:
1095: =cut
1096:
1097: #####################################################
1098: #####################################################
1099: sub store_analysis {
1100: my ($sname,$sdom,$symb,$dataset) = @_;
1101: return if ($symb ne $current_symb);
1102: $cache{$sname.':'.$sdom}=$dataset;
1103: return;
1104: }
1105:
1106: }
1107: #####################################################
1108: #####################################################
1109:
1110: =pod
1111:
1112: =back
1113:
1114: =cut
1115:
1116: #####################################################
1117: #####################################################
1118:
1119: ##
1120: ## The following is copied from datecalc1.pl, part of the
1121: ## Spreadsheet::WriteExcel CPAN module.
1122: ##
1123: ##
1124: ######################################################################
1125: #
1126: # Demonstration of writing date/time cells to Excel spreadsheets,
1127: # using UNIX/Perl time as source of date/time.
1128: #
1129: # Copyright 2000, Andrew Benham, adsb@bigfoot.com
1130: #
1131: ######################################################################
1132: #
1133: # UNIX/Perl time is the time since the Epoch (00:00:00 GMT, 1 Jan 1970)
1134: # measured in seconds.
1135: #
1136: # An Excel file can use exactly one of two different date/time systems.
1137: # In these systems, a floating point number represents the number of days
1138: # (and fractional parts of the day) since a start point. The floating point
1139: # number is referred to as a 'serial'.
1140: # The two systems ('1900' and '1904') use different starting points:
1141: # '1900'; '1.00' is 1 Jan 1900 BUT 1900 is erroneously regarded as
1142: # a leap year - see:
1143: # http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
1144: # for the excuse^H^H^H^H^H^Hreason.
1145: # '1904'; '1.00' is 2 Jan 1904.
1146: #
1147: # The '1904' system is the default for Apple Macs. Windows versions of
1148: # Excel have the option to use the '1904' system.
1149: #
1150: # Note that Visual Basic's "DateSerial" function does NOT erroneously
1151: # regard 1900 as a leap year, and thus its serials do not agree with
1152: # the 1900 serials of Excel for dates before 1 Mar 1900.
1153: #
1154: # Note that StarOffice (at least at version 5.2) does NOT erroneously
1155: # regard 1900 as a leap year, and thus its serials do not agree with
1156: # the 1900 serials of Excel for dates before 1 Mar 1900.
1157: #
1158: ######################################################################
1159: #
1160: # Calculation description
1161: # =======================
1162: #
1163: # 1900 system
1164: # -----------
1165: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 70 years after 1 Jan 1900.
1166: # Of those 70 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
1167: # were leap years with an extra day.
1168: # Thus there were 17 + 70*365 days = 25567 days between 1 Jan 1900 and
1169: # 1 Jan 1970.
1170: # In the 1900 system, '1' is 1 Jan 1900, but as 1900 was not a leap year
1171: # 1 Jan 1900 should really be '2', so 1 Jan 1970 is '25569'.
1172: #
1173: # 1904 system
1174: # -----------
1175: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 66 years after 1 Jan 1904.
1176: # Of those 66 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
1177: # were leap years with an extra day.
1178: # Thus there were 17 + 66*365 days = 24107 days between 1 Jan 1904 and
1179: # 1 Jan 1970.
1180: # In the 1904 system, 2 Jan 1904 being '1', 1 Jan 1970 is '24107'.
1181: #
1182: ######################################################################
1183: #
1184: # Copyright (c) 2000, Andrew Benham.
1185: # This program is free software. It may be used, redistributed and/or
1186: # modified under the same terms as Perl itself.
1187: #
1188: # Andrew Benham, adsb@bigfoot.com
1189: # London, United Kingdom
1190: # 11 Nov 2000
1191: #
1192: ######################################################################
1193: #-----------------------------------------------------------
1194: # calc_serial()
1195: #
1196: # Called with (up to) 2 parameters.
1197: # 1. Unix timestamp. If omitted, uses current time.
1198: # 2. GMT flag. Set to '1' to return serial in GMT.
1199: # If omitted, returns serial in appropriate timezone.
1200: #
1201: # Returns date/time serial according to $DATE_SYSTEM selected
1202: #-----------------------------------------------------------
1203: sub calc_serial {
1204: # Use 1900 date system on all platforms other than Apple Mac (for which
1205: # use 1904 date system).
1206: my $DATE_SYSTEM = ($^O eq 'MacOS') ? 1 : 0;
1207: my $time = (defined $_[0]) ? $_[0] : time();
1208: my $gmtflag = (defined $_[1]) ? $_[1] : 0;
1209: #
1210: # Divide timestamp by number of seconds in a day.
1211: # This gives a date serial with '0' on 1 Jan 1970.
1212: my $serial = $time / 86400;
1213: #
1214: # Adjust the date serial by the offset appropriate to the
1215: # currently selected system (1900/1904).
1216: if ($DATE_SYSTEM == 0) { # use 1900 system
1217: $serial += 25569;
1218: } else { # use 1904 system
1219: $serial += 24107;
1220: }
1221: #
1222: unless ($gmtflag) {
1223: # Now have a 'raw' serial with the right offset. But this
1224: # gives a serial in GMT, which is false unless the timezone
1225: # is GMT. We need to adjust the serial by the appropriate
1226: # timezone offset.
1227: # Calculate the appropriate timezone offset by seeing what
1228: # the differences between localtime and gmtime for the given
1229: # time are.
1230: #
1231: my @gmtime = gmtime($time);
1232: my @ltime = localtime($time);
1233: #
1234: # For the first 7 elements of the two arrays, adjust the
1235: # date serial where the elements differ.
1236: for (0 .. 6) {
1237: my $diff = $ltime[$_] - $gmtime[$_];
1238: if ($diff) {
1239: $serial += _adjustment($diff,$_);
1240: }
1241: }
1242: }
1243: #
1244: # Perpetuate the error that 1900 was a leap year by decrementing
1245: # the serial if we're using the 1900 system and the date is prior to
1246: # 1 Mar 1900. This has the effect of making serial value '60'
1247: # 29 Feb 1900.
1248: #
1249: # This fix only has any effect if UNIX/Perl time on the platform
1250: # can represent 1900. Many can't.
1251: #
1252: unless ($DATE_SYSTEM) {
1253: $serial-- if ($serial < 61); # '61' is 1 Mar 1900
1254: }
1255: return $serial;
1256: }
1257:
1258: sub _adjustment {
1259: # Based on the difference in the localtime/gmtime array elements
1260: # number, return the adjustment required to the serial.
1261: #
1262: # We only look at some elements of the localtime/gmtime arrays:
1263: # seconds unlikely to be different as all known timezones
1264: # have an offset of integral multiples of 15 minutes,
1265: # but it's easy to do.
1266: # minutes will be different for timezone offsets which are
1267: # not an exact number of hours.
1268: # hours very likely to be different.
1269: # weekday will differ when localtime/gmtime difference
1270: # straddles midnight.
1271: #
1272: # Assume that difference between localtime and gmtime is less than
1273: # 5 days, then don't have to do maths for day of month, month number,
1274: # year number, etc...
1275: #
1276: my ($delta,$element) = @_;
1277: my $adjust = 0;
1278: #
1279: if ($element == 0) { # Seconds
1280: $adjust = $delta/86400; # 60 * 60 * 24
1281: } elsif ($element == 1) { # Minutes
1282: $adjust = $delta/1440; # 60 * 24
1283: } elsif ($element == 2) { # Hours
1284: $adjust = $delta/24; # 24
1285: } elsif ($element == 6) { # Day of week number
1286: # Catch difference straddling Sat/Sun in either direction
1287: $delta += 7 if ($delta < -4);
1288: $delta -= 7 if ($delta > 4);
1289: #
1290: $adjust = $delta;
1291: }
1292: return $adjust;
1293: }
1294:
1295: ###########################################################
1296: ###########################################################
1297:
1298: =pod
1299:
1300: =item get_problem_data
1301:
1302: Returns a data structure describing the problem.
1303:
1304: Inputs: $url
1305:
1306: Returns: %Partdata
1307:
1308: =cut
1309:
1310: ## note: we must force each foil and option to not begin or end with
1311: ## spaces as they are stored without such data.
1312: ##
1313: ###########################################################
1314: ###########################################################
1315: sub get_problem_data {
1316: my ($url) = @_;
1317: my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
1318: (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
1319: my %Answer;
1320: %Answer=&Apache::lonnet::str2hash($Answ);
1321: my %Partdata;
1322: foreach my $part (@{$Answer{'parts'}}) {
1323: while (my($key,$value) = each(%Answer)) {
1324: #
1325: # Logging code:
1326: if (0) {
1327: &Apache::lonnet::logthis($part.' got key "'.$key.'"');
1328: if (ref($value) eq 'ARRAY') {
1329: &Apache::lonnet::logthis(' @'.join(',',@$value));
1330: } else {
1331: &Apache::lonnet::logthis(' '.$value);
1332: }
1333: }
1334: # End of logging code
1335: next if ($key !~ /^\Q$part\E/);
1336: $key =~ s/^\Q$part\E\.//;
1337: if (ref($value) eq 'ARRAY') {
1338: if ($key eq 'options') {
1339: $Partdata{$part}->{'_Options'}=$value;
1340: } elsif ($key eq 'concepts') {
1341: $Partdata{$part}->{'_Concepts'}=$value;
1342: } elsif ($key eq 'items') {
1343: $Partdata{$part}->{'_Items'}=$value;
1344: } elsif ($key =~ /^concept\.(.*)$/) {
1345: my $concept = $1;
1346: foreach my $foil (@$value) {
1347: $Partdata{$part}->{'_Foils'}->{$foil}->{'_Concept'}=
1348: $concept;
1349: }
1350: } elsif ($key =~ /^(unit|incorrect|answer|ans_low|ans_high|str_type)$/) {
1351: $Partdata{$part}->{$key}=$value;
1352: }
1353: } else {
1354: if ($key=~ /^foil\.text\.(.*)$/) {
1355: my $foil = $1;
1356: $Partdata{$part}->{'_Foils'}->{$foil}->{'name'}=$foil;
1357: $value =~ s/(\s*$|^\s*)//g;
1358: $Partdata{$part}->{'_Foils'}->{$foil}->{'text'}=$value;
1359: } elsif ($key =~ /^foil\.value\.(.*)$/) {
1360: my $foil = $1;
1361: $Partdata{$part}->{'_Foils'}->{$foil}->{'value'}=$value;
1362: } elsif ($key eq 'answercomputed') {
1363: $Partdata{$part}->{'answercomputed'} = $value;
1364: }
1365: }
1366: }
1367: }
1368: # Further debugging code
1369: if (0) {
1370: &Apache::lonnet::logthis('lonstathelpers::get_problem_data');
1371: &log_hash_ref(\%Partdata);
1372: }
1373: return %Partdata;
1374: }
1375:
1376: sub log_array_ref {
1377: my ($arrayref,$prefix) = @_;
1378: return if (ref($arrayref) ne 'ARRAY');
1379: if (! defined($prefix)) { $prefix = ''; };
1380: foreach my $v (@$arrayref) {
1381: if (ref($v) eq 'ARRAY') {
1382: &log_array_ref($v,$prefix.' ');
1383: } elsif (ref($v) eq 'HASH') {
1384: &log_hash_ref($v,$prefix.' ');
1385: } else {
1386: &Apache::lonnet::logthis($prefix.'"'.$v.'"');
1387: }
1388: }
1389: }
1390:
1391: sub log_hash_ref {
1392: my ($hashref,$prefix) = @_;
1393: return if (ref($hashref) ne 'HASH');
1394: if (! defined($prefix)) { $prefix = ''; };
1395: while (my ($k,$v) = each(%$hashref)) {
1396: if (ref($v) eq 'ARRAY') {
1397: &Apache::lonnet::logthis($prefix.'"'.$k.'" = array');
1398: &log_array_ref($v,$prefix.' ');
1399: } elsif (ref($v) eq 'HASH') {
1400: &Apache::lonnet::logthis($prefix.'"'.$k.'" = hash');
1401: &log_hash_ref($v,$prefix.' ');
1402: } else {
1403: &Apache::lonnet::logthis($prefix.'"'.$k.'" => "'.$v.'"');
1404: }
1405: }
1406: }
1407: ####################################################
1408: ####################################################
1409:
1410: =pod
1411:
1412: =item &limit_by_time()
1413:
1414: =cut
1415:
1416: ####################################################
1417: ####################################################
1418: sub limit_by_time_form {
1419: my $Starttime_form = '';
1420: my $starttime = &Apache::lonhtmlcommon::get_date_from_form
1421: ('limitby_startdate');
1422: my $endtime = &Apache::lonhtmlcommon::get_date_from_form
1423: ('limitby_enddate');
1424: if (! defined($endtime)) {
1425: $endtime = time;
1426: }
1427: if (! defined($starttime)) {
1428: $starttime = $endtime - 60*60*24*7;
1429: }
1430: my $state;
1431: if (&limit_by_time()) {
1432: $state = '';
1433: } else {
1434: $state = 'disabled';
1435: }
1436: my $startdateform = &Apache::lonhtmlcommon::date_setter
1437: ('Statistics','limitby_startdate',$starttime,undef,undef,$state);
1438: my $enddateform = &Apache::lonhtmlcommon::date_setter
1439: ('Statistics','limitby_enddate',$endtime,undef,undef,$state);
1440: my $Str;
1441: $Str .= '<script type="text/javascript" language="JavaScript">';
1442: $Str .= 'function toggle_limitby_activity(state) {';
1443: $Str .= ' if (state) {';
1444: $Str .= ' limitby_startdate_enable();';
1445: $Str .= ' limitby_enddate_enable();';
1446: $Str .= ' } else {';
1447: $Str .= ' limitby_startdate_disable();';
1448: $Str .= ' limitby_enddate_disable();';
1449: $Str .= ' }';
1450: $Str .= '}';
1451: $Str .= '</script>';
1452: $Str .= '<fieldset>';
1453: my $timecheckbox = '<input type="checkbox" name="limit_by_time" ';
1454: if (&limit_by_time()) {
1455: $timecheckbox .= 'checked="checked" ';
1456: }
1457: $timecheckbox .= 'onchange="javascript:toggle_limitby_activity(this.checked);" ';
1458: $timecheckbox .= ' />';
1459: $Str .= '<legend><label>'.&mt('[_1] Limit by time',$timecheckbox).'</label></legend>';
1460: $Str .= &mt('Start Time: [_1]',$startdateform).'<br />';
1461: $Str .= &mt(' End Time: [_1]',$enddateform).'<br />';
1462: $Str .= '</fieldset>';
1463: return $Str;
1464: }
1465:
1466: sub limit_by_time {
1467: if (exists($env{'form.limit_by_time'}) &&
1468: $env{'form.limit_by_time'} ne '' ) {
1469: return 1;
1470: } else {
1471: return 0;
1472: }
1473: }
1474:
1475: sub get_time_limits {
1476: my $starttime = &Apache::lonhtmlcommon::get_date_from_form
1477: ('limitby_startdate');
1478: my $endtime = &Apache::lonhtmlcommon::get_date_from_form
1479: ('limitby_enddate');
1480: return ($starttime,$endtime);
1481: }
1482:
1483: ####################################################
1484: ####################################################
1485:
1486: =pod
1487:
1488: =item &manage_caches
1489:
1490: Inputs: $r, apache request object
1491:
1492: Returns: An array of scalars containing html for buttons.
1493:
1494: =cut
1495:
1496: ####################################################
1497: ####################################################
1498: sub manage_caches {
1499: my ($r,$formname,$inputname,$update_message) = @_;
1500: &Apache::loncoursedata::clear_internal_caches();
1501: my $sectionkey =
1502: join(',',
1503: map {
1504: &escape($_);
1505: } sort(&Apache::lonstatistics::get_selected_sections())
1506: );
1507: my $statuskey = $Apache::lonstatistics::enrollment_status;
1508: if (exists($env{'form.ClearCache'}) ||
1509: exists($env{'form.updatecaches'}) ||
1510: (exists($env{'form.firstrun'}) && $env{'form.firstrun'} ne 'no') ||
1511: (exists($env{'form.prevsection'}) &&
1512: $env{'form.prevsection'} ne $sectionkey) ||
1513: (exists($env{'form.prevenrollstatus'}) &&
1514: $env{'form.prevenrollstatus'} ne $statuskey)
1515: ) {
1516: if (defined($update_message)) {
1517: $r->print($update_message);
1518: }
1519: if (0) {
1520: &Apache::lonnet::logthis('Updating mysql student data caches');
1521: }
1522: &gather_full_student_data($r,$formname,$inputname);
1523: }
1524: #
1525: my @Buttons =
1526: ('<input type="submit" name="ClearCache" '.
1527: 'value="'.&mt('Clear Caches').'" />',
1528: '<input type="submit" name="updatecaches" '.
1529: 'value="'.&mt('Update Caches').'" />'.
1530: &Apache::loncommon::help_open_topic('Statistics_Cache'),
1531: '<input type="hidden" name="prevsection" value="'.$sectionkey.'" />',
1532: '<input type="hidden" name="prevenrollstatus" value="'.$statuskey.'" />'
1533: );
1534: #
1535: if (! exists($env{'form.firstrun'})) {
1536: $r->print('<input type="hidden" name="firstrun" value="yes" />');
1537: } else {
1538: $r->print('<input type="hidden" name="firstrun" value="no" />');
1539: }
1540: #
1541: return @Buttons;
1542: }
1543:
1544: sub gather_full_student_data {
1545: my ($r,$formname,$inputname) = @_;
1546: my $status_type;
1547: if (defined($formname)) {
1548: $status_type = 'inline';
1549: } else {
1550: $status_type = 'popup';
1551: }
1552: my $c = $r->connection();
1553: #
1554: &Apache::loncoursedata::clear_internal_caches();
1555: #
1556: my @Students = @Apache::lonstatistics::Students;
1557: #
1558: # Open the progress window
1559: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,scalar(@Students));
1560: #
1561: while (my $student = shift @Students) {
1562: return if ($c->aborted());
1563: my $status = &Apache::loncoursedata::ensure_current_full_data
1564: ($student->{'username'},$student->{'domain'},
1565: $env{'request.course.id'});
1566: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
1567: &mt('last student'));
1568: }
1569: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1570: $r->rflush();
1571: return;
1572: }
1573:
1574: ####################################################
1575: ####################################################
1576:
1577: =pod
1578:
1579: =item &submission_report_form
1580:
1581: Input: The originating reportSelected value for the current stats page.
1582:
1583: Output: Scalar containing HTML with needed form elements and a link to
1584: the student submission reports page.
1585:
1586: =cut
1587:
1588: ####################################################
1589: ####################################################
1590: sub submission_report_form {
1591: my ($original_report) = @_;
1592: # Note: In the link below we change the reportSelected value. If
1593: # the user hits the 'back' button on the browser after getting their
1594: # student submissions report, this value may still be around. So we
1595: # output a script block to set it properly. If the $original_report
1596: # value is unset, you are just asking for trouble.
1597: if (! defined($original_report)) {
1598: &Apache::lonnet::logthis
1599: ('someone called lonstathelpers::submission_report_form without '.
1600: ' enough input.');
1601: }
1602: my $html = $/.
1603: '<script type="text/javascript" language="JavaScript">'.
1604: "document.Statistics.reportSelected.value='$original_report';".
1605: '</script>'.
1606: '<input type="hidden" name="correctans" value="true" />'.
1607: '<input type="hidden" name="prob_status" value="true" />'.
1608: '<input type="hidden" name="all_sub" value="true" />';
1609: my $output_selector = $/.'<select name="output">'.$/;
1610: foreach ('HTML','Excel','CSV') {
1611: $output_selector .= ' <option value="'.lc($_).'"';
1612: if ($env{'form.output'} eq lc($_)) {
1613: $output_selector .= ' selected ';
1614: }
1615: $output_selector .='>'.&mt($_).'</option>'.$/;
1616: }
1617: $output_selector .= '</select>'.$/;
1618: my $link = '<a href="javascript:'.
1619: q{document.Statistics.reportSelected.value='student_submission_reports';}.
1620: 'document.Statistics.submit();">';
1621: $html.= &mt('View data as [_1] [_2]go[_3]',$output_selector,
1622: $link,'</a>').$/;
1623: return $html
1624: }
1625:
1626: ####################################################
1627: ####################################################
1628:
1629: =pod
1630:
1631: =back
1632:
1633: =cut
1634:
1635: ####################################################
1636: ####################################################
1637:
1638: 1;
1639:
1640: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>