File:
[LON-CAPA] /
loncom /
interface /
lonnavmaps.pm
Revision
1.201:
download - view:
text,
annotated -
select for diffs
Thu Jun 12 20:36:41 2003 UTC (21 years, 1 month ago) by
bowersj2
Branches:
MAIN
CVS tags:
HEAD
Misc. fixups: .pages show in Show Only Homework view. Empty .pages are
suppressed in the Show Only Homework view. Folders can not be opened or
closed in the Show Only Homework mode, because it plays havoc with the
system and it's not worth fixing; clicking on folders like that really
has poorly defined semantics and the user would be just guessing what
would happen when some of the map is suppressed.
1: # The LearningOnline Network with CAPA
2: # Navigate Maps Handler
3: #
4: # $Id: lonnavmaps.pm,v 1.201 2003/06/12 20:36:41 bowersj2 Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: # (Page Handler
29: #
30: # (TeX Content Handler
31: #
32: # 05/29/00,05/30 Gerd Kortemeyer)
33: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
34: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
35: #
36: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
37: # YEAR=2002
38: # 1/1 Gerd Kortemeyer
39: # Oct-Nov Jeremy Bowers
40: # YEAR=2003
41: # Jeremy Bowers ... lots of days
42:
43: package Apache::lonnavmaps;
44:
45: use strict;
46: use Apache::Constants qw(:common :http);
47: use Apache::loncommon();
48: use Apache::lonmenu();
49: use POSIX qw (floor strftime);
50: use Data::Dumper; # for debugging, not always used
51:
52: # symbolic constants
53: sub SYMB { return 1; }
54: sub URL { return 2; }
55: sub NOTHING { return 3; }
56:
57: # Some data
58:
59: my $resObj = "Apache::lonnavmaps::resource";
60:
61: # Keep these mappings in sync with lonquickgrades, which uses the colors
62: # instead of the icons.
63: my %statusIconMap =
64: ( $resObj->NETWORK_FAILURE => '',
65: $resObj->NOTHING_SET => '',
66: $resObj->CORRECT => 'navmap.correct.gif',
67: $resObj->EXCUSED => 'navmap.correct.gif',
68: $resObj->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
69: $resObj->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
70: $resObj->ANSWER_OPEN => 'navmap.wrong.gif',
71: $resObj->OPEN_LATER => '',
72: $resObj->TRIES_LEFT => 'navmap.open.gif',
73: $resObj->INCORRECT => 'navmap.wrong.gif',
74: $resObj->OPEN => 'navmap.open.gif',
75: $resObj->ATTEMPTED => 'navmap.ellipsis.gif',
76: $resObj->ANSWER_SUBMITTED => '' );
77:
78: my %iconAltTags =
79: ( 'navmap.correct.gif' => 'Correct',
80: 'navmap.wrong.gif' => 'Incorrect',
81: 'navmap.open.gif' => 'Open' );
82:
83: # Defines a status->color mapping, null string means don't color
84: my %colormap =
85: ( $resObj->NETWORK_FAILURE => '',
86: $resObj->CORRECT => '',
87: $resObj->EXCUSED => '#3333FF',
88: $resObj->PAST_DUE_ANSWER_LATER => '',
89: $resObj->PAST_DUE_NO_ANSWER => '',
90: $resObj->ANSWER_OPEN => '#006600',
91: $resObj->OPEN_LATER => '',
92: $resObj->TRIES_LEFT => '',
93: $resObj->INCORRECT => '',
94: $resObj->OPEN => '',
95: $resObj->NOTHING_SET => '' );
96: # And a special case in the nav map; what to do when the assignment
97: # is not yet done and due in less then 24 hours
98: my $hurryUpColor = "#FF0000";
99:
100: sub handler {
101: my $r = shift;
102: real_handler($r);
103: }
104:
105: sub real_handler {
106: my $r = shift;
107:
108: # Handle header-only request
109: if ($r->header_only) {
110: if ($ENV{'browser.mathml'}) {
111: $r->content_type('text/xml');
112: } else {
113: $r->content_type('text/html');
114: }
115: $r->send_http_header;
116: return OK;
117: }
118:
119: # Send header, don't cache this page
120: if ($ENV{'browser.mathml'}) {
121: $r->content_type('text/xml');
122: } else {
123: $r->content_type('text/html');
124: }
125: &Apache::loncommon::no_cache($r);
126: $r->send_http_header;
127:
128: # Create the nav map
129: my $navmap = Apache::lonnavmaps::navmap->new(
130: $ENV{"request.course.fn"}.".db",
131: $ENV{"request.course.fn"}."_parms.db", 1, 1);
132:
133:
134: if (!defined($navmap)) {
135: my $requrl = $r->uri;
136: $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
137: return HTTP_NOT_ACCEPTABLE;
138: }
139:
140: $r->print("<html><head>\n");
141: $r->print("<title>Navigate Course Contents</title>");
142: # ------------------------------------------------------------ Get query string
143: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['register']);
144:
145: # ----------------------------------------------------- Force menu registration
146: my $addentries='';
147: if ($ENV{'form.register'}) {
148: $addentries=' onLoad="'.&Apache::lonmenu::loadevents().
149: '" onUnload="'.&Apache::lonmenu::unloadevents().'"';
150: $r->print(&Apache::lonmenu::registerurl(1));
151: }
152:
153: # Header
154: $r->print('</head>'.
155: &Apache::loncommon::bodytag('Navigate Course Contents','',
156: $addentries,'','',$ENV{'form.register'}));
157: $r->print('<script>window.focus();</script>');
158:
159: $r->rflush();
160:
161: # Now that we've displayed some stuff to the user, init the navmap
162: $navmap->init();
163:
164: $r->print('<br> ');
165: $r->rflush();
166:
167: # Check that it's defined
168: if (!($navmap->courseMapDefined())) {
169: $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
170: '</body></html>');
171: return OK;
172: }
173:
174: # See if there's only one map in the top-level, if we don't
175: # already have a filter... if so, automatically display it
176: if ($ENV{QUERY_STRING} !~ /filter/) {
177: my $iterator = $navmap->getIterator(undef, undef, undef, 0);
178: my $depth = 1;
179: $iterator->next();
180: my $curRes = $iterator->next();
181: my $sequenceCount = 0;
182: my $sequenceId;
183: while ($depth > 0) {
184: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
185: if ($curRes == $iterator->END_MAP()) { $depth--; }
186:
187: if (ref($curRes) && $curRes->is_sequence()) {
188: $sequenceCount++;
189: $sequenceId = $curRes->map_pc();
190: }
191:
192: $curRes = $iterator->next();
193: }
194:
195: if ($sequenceCount == 1) {
196: # The automatic iterator creation in the render call
197: # will pick this up. We know the condition because
198: # the defined($ENV{'form.filter'}) also ensures this
199: # is a fresh call.
200: $ENV{'form.filter'} = "$sequenceId";
201: }
202: }
203:
204: my $jumpToFirstHomework = 0;
205: # Check to see if the student is jumping to next open, do-able problem
206: if ($ENV{QUERY_STRING} eq 'jumpToFirstHomework') {
207: $jumpToFirstHomework = 1;
208: # Find the next homework problem that they can do.
209: my $iterator = $navmap->getIterator(undef, undef, undef, 1);
210: my $depth = 1;
211: $iterator->next();
212: my $curRes = $iterator->next();
213: my $foundDoableProblem = 0;
214: my $problemRes;
215:
216: while ($depth > 0 && !$foundDoableProblem) {
217: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
218: if ($curRes == $iterator->END_MAP()) { $depth--; }
219:
220: if (ref($curRes) && $curRes->is_problem()) {
221: my $status = $curRes->status();
222: if ($curRes->completable()) {
223: $problemRes = $curRes;
224: $foundDoableProblem = 1;
225:
226: # Pop open all previous maps
227: my $stack = $iterator->getStack();
228: pop @$stack; # last resource in the stack is the problem
229: # itself, which we don't need in the map stack
230: my @mapPcs = map {$_->map_pc()} @$stack;
231: $ENV{'form.filter'} = join(',', @mapPcs);
232:
233: # Mark as both "here" and "jump"
234: $ENV{'form.postsymb'} = $curRes->symb();
235: }
236: }
237: } continue {
238: $curRes = $iterator->next();
239: }
240:
241: # If we found no problems, print a note to that effect.
242: if (!$foundDoableProblem) {
243: $r->print("<font size='+2'>All homework assignments have been completed.</font><br /><br />");
244: }
245: } else {
246: $r->print("<a href='navmaps?jumpToFirstHomework'>" .
247: "Go To My First Homework Problem</a><br />");
248: }
249:
250: my $suppressEmptySequences = 0;
251: my $filterFunc = undef;
252: my $resource_no_folder_link = 0;
253:
254: # Display only due homework.
255: my $showOnlyHomework = 0;
256: if ($ENV{QUERY_STRING} eq 'showOnlyHomework') {
257: $showOnlyHomework = 1;
258: $suppressEmptySequences = 1;
259: $filterFunc = sub { my $res = shift;
260: return $res->completable() || $res->is_map();
261: };
262: $r->print("<p><font size='+2'>Uncompleted Homework</font></p>");
263: $ENV{'form.filter'} = '';
264: $ENV{'form.condition'} = 1;
265: $resource_no_folder_link = 1;
266: } else {
267: $r->print("<a href='navmaps?showOnlyHomework'>" .
268: "Show Only Uncompleted Homework</a><br />");
269: }
270:
271: # renderer call
272: my $renderArgs = { 'cols' => [0,1,2,3],
273: 'url' => '/adm/navmaps',
274: 'navmap' => $navmap,
275: 'suppressNavmap' => 1,
276: 'suppressEmptySequences' => $suppressEmptySequences,
277: 'filterFunc' => $filterFunc,
278: 'resource_no_folder_link' => $resource_no_folder_link,
279: 'r' => $r};
280: my $render = render($renderArgs);
281: $navmap->untieHashes();
282:
283: # If no resources were printed, print a reassuring message so the
284: # user knows there was no error.
285: if ($renderArgs->{'counter'} == 0) {
286: if ($showOnlyHomework) {
287: $r->print("<p><font size='+1'>All homework is currently completed.</font></p>");
288: } else { # both jumpToFirstHomework and normal use the same: course must be empty
289: $r->print("<p><font size='+1'>This course is empty.</font></p>");
290: }
291: }
292:
293: $r->print("</body></html>");
294: $r->rflush();
295:
296: return OK;
297: }
298:
299: # Convenience functions: Returns a string that adds or subtracts
300: # the second argument from the first hash, appropriate for the
301: # query string that determines which folders to recurse on
302: sub addToFilter {
303: my $hashIn = shift;
304: my $addition = shift;
305: my %hash = %$hashIn;
306: $hash{$addition} = 1;
307:
308: return join (",", keys(%hash));
309: }
310:
311: sub removeFromFilter {
312: my $hashIn = shift;
313: my $subtraction = shift;
314: my %hash = %$hashIn;
315:
316: delete $hash{$subtraction};
317: return join(",", keys(%hash));
318: }
319:
320: # Convenience function: Given a stack returned from getStack on the iterator,
321: # return the correct src() value.
322: # Later, this should add an anchor when we start putting anchors in pages.
323: sub getLinkForResource {
324: my $stack = shift;
325: my $res;
326:
327: # Check to see if there are any pages in the stack
328: foreach $res (@$stack) {
329: if (defined($res) && $res->is_page()) {
330: return $res->src();
331: }
332: }
333:
334: # Failing that, return the src of the last resource that is defined
335: # (when we first recurse on a map, it puts an undefined resource
336: # on the bottom because $self->{HERE} isn't defined yet, and we
337: # want the src for the map anyhow)
338: foreach (@$stack) {
339: if (defined($_)) { $res = $_; }
340: }
341:
342: return $res->src();
343: }
344:
345: # Convenience function: This seperates the logic of how to create
346: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
347: # etc.) into a seperate function. It takes a resource object as the
348: # first parameter, and the part number of the resource as the second.
349: # It's basically a big switch statement on the status of the resource.
350:
351: sub getDescription {
352: my $res = shift;
353: my $part = shift;
354: my $status = $res->status($part);
355:
356: if ($status == $res->NETWORK_FAILURE) {
357: return "Having technical difficulties; please check status later";
358: }
359: if ($status == $res->NOTHING_SET) {
360: return "Not currently assigned.";
361: }
362: if ($status == $res->OPEN_LATER) {
363: return "Open " . timeToHumanString($res->opendate($part));
364: }
365: if ($status == $res->OPEN) {
366: if ($res->duedate($part)) {
367: return "Due " . timeToHumanString($res->duedate($part));
368: } else {
369: return "Open, no due date";
370: }
371: }
372: if ($status == $res->PAST_DUE_ANSWER_LATER) {
373: return "Answer open " . timeToHumanString($res->answerdate($part));
374: }
375: if ($status == $res->PAST_DUE_NO_ANSWER) {
376: return "Was due " . timeToHumanString($res->duedate($part));
377: }
378: if ($status == $res->ANSWER_OPEN) {
379: return "Answer available";
380: }
381: if ($status == $res->EXCUSED) {
382: return "Excused by instructor";
383: }
384: if ($status == $res->ATTEMPTED) {
385: return "Answer submitted, not yet graded.";
386: }
387: if ($status == $res->TRIES_LEFT) {
388: my $tries = $res->tries($part);
389: my $maxtries = $res->maxtries($part);
390: my $triesString = "";
391: if ($tries && $maxtries) {
392: $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
393: if ($maxtries > 1 && $maxtries - $tries == 1) {
394: $triesString = "<b>$triesString</b>";
395: }
396: }
397: if ($res->duedate()) {
398: return "Due " . timeToHumanString($res->duedate($part)) .
399: " $triesString";
400: } else {
401: return "No due date $triesString";
402: }
403: }
404: if ($status == $res->ANSWER_SUBMITTED) {
405: return 'Answer submitted';
406: }
407: }
408:
409: # Convenience function, so others can use it: Is the problem due in less then
410: # 24 hours, and still can be done?
411:
412: sub dueInLessThen24Hours {
413: my $res = shift;
414: my $part = shift;
415: my $status = $res->status($part);
416:
417: return ($status == $res->OPEN() || $status == $res->ATTEMPTED() ||
418: $status == $res->TRIES_LEFT()) &&
419: $res->duedate() && $res->duedate() < time()+(24*60*60) &&
420: $res->duedate() > time();
421: }
422:
423: # Convenience function, so others can use it: Is there only one try remaining for the
424: # part, with more then one try to begin with, not due yet and still can be done?
425: sub lastTry {
426: my $res = shift;
427: my $part = shift;
428:
429: my $tries = $res->tries($part);
430: my $maxtries = $res->maxtries($part);
431: return $tries && $maxtries && $maxtries > 1 &&
432: $maxtries - $tries == 1 && $res->duedate() &&
433: $res->duedate() > time();
434: }
435:
436: # This puts a human-readable name on the ENV variable.
437:
438: sub advancedUser {
439: return $ENV{'request.role.adv'};
440: }
441:
442:
443: # timeToHumanString takes a time number and converts it to a
444: # human-readable representation, meant to be used in the following
445: # manner:
446: # print "Due $timestring"
447: # print "Open $timestring"
448: # print "Answer available $timestring"
449: # Very, very, very, VERY English-only... goodness help a localizer on
450: # this func...
451: sub timeToHumanString {
452: my ($time) = @_;
453: # zero, '0' and blank are bad times
454: if (!$time) {
455: return 'never';
456: }
457:
458: my $now = time();
459:
460: my @time = localtime($time);
461: my @now = localtime($now);
462:
463: # Positive = future
464: my $delta = $time - $now;
465:
466: my $minute = 60;
467: my $hour = 60 * $minute;
468: my $day = 24 * $hour;
469: my $week = 7 * $day;
470: my $inPast = 0;
471:
472: # Logic in comments:
473: # Is it now? (extremely unlikely)
474: if ( $delta == 0 ) {
475: return "this instant";
476: }
477:
478: if ($delta < 0) {
479: $inPast = 1;
480: $delta = -$delta;
481: }
482:
483: if ( $delta > 0 ) {
484:
485: my $tense = $inPast ? " ago" : "";
486: my $prefix = $inPast ? "" : "in ";
487:
488: # Less then a minute
489: if ( $delta < $minute ) {
490: if ($delta == 1) { return "${prefix}1 second$tense"; }
491: return "$prefix$delta seconds$tense";
492: }
493:
494: # Less then an hour
495: if ( $delta < $hour ) {
496: # If so, use minutes
497: my $minutes = floor($delta / 60);
498: if ($minutes == 1) { return "${prefix}1 minute$tense"; }
499: return "$prefix$minutes minutes$tense";
500: }
501:
502: # Is it less then 24 hours away? If so,
503: # display hours + minutes
504: if ( $delta < $hour * 24) {
505: my $hours = floor($delta / $hour);
506: my $minutes = floor(($delta % $hour) / $minute);
507: my $hourString = "$hours hours";
508: my $minuteString = ", $minutes minutes";
509: if ($hours == 1) {
510: $hourString = "1 hour";
511: }
512: if ($minutes == 1) {
513: $minuteString = ", 1 minute";
514: }
515: if ($minutes == 0) {
516: $minuteString = "";
517: }
518: return "$prefix$hourString$minuteString$tense";
519: }
520:
521: # Less then 5 days away, display day of the week and
522: # HH:MM
523: if ( $delta < $day * 5 ) {
524: my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
525: $timeStr =~ s/12:00 am/midnight/;
526: $timeStr =~ s/12:00 pm/noon/;
527: return ($inPast ? "last " : "next ") .
528: $timeStr;
529: }
530:
531: # Is it this year?
532: if ( $time[5] == $now[5]) {
533: # Return on Month Day, HH:MM meridian
534: my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
535: $timeStr =~ s/12:00 am/midnight/;
536: $timeStr =~ s/12:00 pm/noon/;
537: return $timeStr;
538: }
539:
540: # Not this year, so show the year
541: my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
542: $timeStr =~ s/12:00 am/midnight/;
543: $timeStr =~ s/12:00 pm/noon/;
544: return $timeStr;
545: }
546: }
547:
548:
549: =pod
550:
551: =head1 NAME
552:
553: Apache::lonnavmap - Subroutines to handle and render the navigation maps
554:
555: =head1 SYNOPSIS
556:
557: The main handler generates the navigational listing for the course,
558: the other objects export this information in a usable fashion for
559: other modules
560:
561: =head1 Object: render
562:
563: The navmap renderer package provides a sophisticated rendering of the
564: standard navigation maps interface into HTML. The provided nav map
565: handler is actually just a glorified call to this.
566:
567: Because of the large number of parameters this function presents,
568: instead of passing it arguments as is normal, pass it in an anonymous
569: hash with the given options. This is because there is no obvious order
570: you may wish to override these in and a hash is easier to read and
571: understand then "undef, undef, undef, 1, undef, undef, renderButton,
572: undef, 0" when you mostly want default behaviors.
573:
574: The package provides a function called 'render', called as
575: Apache::lonnavmaps::renderer->render({}).
576:
577: =head2 Overview of Columns
578:
579: The renderer will build an HTML table for the navmap and return
580: it. The table is consists of several columns, and a row for each
581: resource (or possibly each part). You tell the renderer how many
582: columns to create and what to place in each column, optionally using
583: one or more of the preparent columns, and the renderer will assemble
584: the table.
585:
586: Any additional generally useful column types should be placed in the
587: renderer code here, so anybody can use it anywhere else. Any code
588: specific to the current application (such as the addition of <input>
589: elements in a column) should be placed in the code of the thing using
590: the renderer.
591:
592: At the core of the renderer is the array reference COLS (see Example
593: section below for how to pass this correctly). The COLS array will
594: consist of entries of one of two types of things: Either an integer
595: representing one of the pre-packaged column types, or a sub reference
596: that takes a resource reference, a part number, and a reference to the
597: argument hash passed to the renderer, and returns a string that will
598: be inserted into the HTML representation as it.
599:
600: The pre-packaged column names are refered to by constants in the
601: Apache::lonnavmaps::renderer namespace. The following currently exist:
602:
603: =over 4
604:
605: =item * B<resource>:
606:
607: The general info about the resource: Link, icon for the type, etc. The
608: first column in the standard nav map display. This column also accepts
609: the following parameter in the renderer hash:
610:
611: =over 4
612:
613: =item * B<resource_nolink>:
614:
615: If true, the resource will not be linked. Default: false, resource
616: will have links.
617:
618: =item * B<resource_part_count>:
619:
620: If true (default), the resource will show a part count if the full
621: part list is not displayed. If false, the resource will never show a
622: part count.
623:
624: =item * B<resource_no_folder_link>:
625:
626: If true, the resource's folder will not be clickable to open or close
627: it. Default is false. True implies printCloseAll is false, since you
628: can't close or open folders when this is on anyhow.
629:
630: =back
631:
632: =item B<communication_status>:
633:
634: Whether there is discussion on the resource, email for the user, or
635: (lumped in here) perl errors in the execution of the problem. This is
636: the second column in the main nav map.
637:
638: =item B<quick_status>:
639:
640: An icon for the status of a problem, with four possible states:
641: Correct, incorrect, open, or none (not open yet, not a problem). The
642: third column of the standard navmap.
643:
644: =item B<long_status>:
645:
646: A text readout of the details of the current status of the problem,
647: such as "Due in 22 hours". The fourth column of the standard navmap.
648:
649: =back
650:
651: If you add any others please be sure to document them here.
652:
653: An example of a column renderer that will show the ID number of a
654: resource, along with the part name if any:
655:
656: sub {
657: my ($resource, $part, $params) = @_;
658: if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
659: return '<td>' . $resource->{ID} . '</td>';
660: }
661:
662: Note these functions are responsible for the TD tags, which allow them
663: to override vertical and horizontal alignment, etc.
664:
665: =head2 Parameters
666:
667: Most of these parameters are only useful if you are *not* using the
668: folder interface (i.e., the default first column), which is probably
669: the common case. If you are using this interface, then you should be
670: able to get away with just using 'cols' (to specify the columns
671: shown), 'url' (necessary for the folders to link to the current screen
672: correctly), and possibly 'queryString' if your app calls for it. In
673: that case, maintaining the state of the folders will be done
674: automatically.
675:
676: =over 4
677:
678: =item * B<iterator>:
679:
680: A reference to a fresh ::iterator to use from the navmaps. The
681: rendering will reflect the options passed to the iterator, so you can
682: use that to just render a certain part of the course, if you like. If
683: one is not passed, the renderer will attempt to construct one from
684: ENV{'form.filter'} and ENV{'form.condition'} information, plus the
685: 'iterator_map' parameter if any.
686:
687: =item * B<iterator_map>:
688:
689: If you are letting the renderer do the iterator handling, you can
690: instruct the renderer to render only a particular map by passing it
691: the source of the map you want to process, like
692: '/res/103/jerf/navmap.course.sequence'.
693:
694: =item * B<navmap>:
695:
696: A reference to a navmap, used only if an iterator is not passed in. If
697: this is necessary to make an iterator but it is not passed in, a new
698: one will be constructed based on ENV info. This is useful to do basic
699: error checking before passing it off to render.
700:
701: =item * B<r>:
702:
703: The standard Apache response object. This must be passed to the
704: renderer or the course hash will be locked.
705:
706: =item * B<cols>:
707:
708: An array reference
709:
710: =item * B<showParts>:
711:
712: A flag. If yes (default), a line for the resource itself, and a line
713: for each part will be displayed. If not, only one line for each
714: resource will be displayed.
715:
716: =item * B<condenseParts>:
717:
718: A flag. If yes (default), if all parts of the problem have the same
719: status and that status is Nothing Set, Correct, or Network Failure,
720: then only one line will be displayed for that resource anyhow. If no,
721: all parts will always be displayed. If showParts is 0, this is
722: ignored.
723:
724: =item * B<jumpCount>:
725:
726: A string identifying the URL to place the anchor 'curloc' at. Default
727: to no anchor at all. It is the responsibility of the renderer user to
728: ensure that the #curloc is in the URL. By default, determined through
729: the use of the ENV{} 'jump' information, and should normally "just
730: work" correctly.
731:
732: =item * B<here>:
733:
734: A Symb identifying where to place the 'here' marker. Default empty,
735: which means no marker.
736:
737: =item * B<indentString>:
738:
739: A string identifying the indentation string to use. By default, this
740: is a 25 pixel whitespace image with no alt text.
741:
742: =item * B<queryString>:
743:
744: A string which will be prepended to the query string used when the
745: folders are opened or closed.
746:
747: =item * B<url>:
748:
749: The url the folders will link to, which should be the current
750: page. Required if the resource info column is shown.
751:
752: =item * B<currentJumpIndex>:
753:
754: Describes the currently-open row number to cause the browser to jump
755: to, because the user just opened that folder. By default, pulled from
756: the Jump information in the ENV{'form.*'}.
757:
758: =item * B<printKey>:
759:
760: If true, print the key that appears on the top of the standard
761: navmaps. Default is false.
762:
763: =item * B<printCloseAll>:
764:
765: If true, print the "Close all folders" or "open all folders"
766: links. Default is true.
767:
768: =item * B<filterFunc>:
769:
770: A function that takes the resource object as its only parameter and
771: returns a true or false value. If true, the resource is displayed. If
772: false, it is simply skipped in the display. By default, all resources
773: are shown.
774:
775: =item * B<suppressEmptySequences>:
776:
777: If you're using a filter function, and displaying sequences to orient
778: the user, then frequently some sequences will be empty. Setting this to
779: true will cause those sequences not to display, so as not to confuse the
780: user into thinking that if the sequence is there there should be things
781: under it.
782:
783: =item * B<suppressNavmaps>:
784:
785: If true, will not display Navigate Content resources. Default to
786: false.
787:
788: =back
789:
790: =head2 Additional Info
791:
792: In addition to the parameters you can pass to the renderer, which will
793: be passed through unchange to the column renderers, the renderer will
794: generate the following information which your renderer may find
795: useful:
796:
797: If you want to know how many rows were printed, the 'counter' element
798: of the hash passed into the render function will contain the
799: count. You may want to check whether any resources were printed at
800: all.
801:
802: =over 4
803:
804: =back
805:
806: =cut
807:
808: sub resource { return 0; }
809: sub communication_status { return 1; }
810: sub quick_status { return 2; }
811: sub long_status { return 3; }
812:
813: # Data for render_resource
814:
815: sub render_resource {
816: my ($resource, $part, $params) = @_;
817:
818: my $nonLinkedText = ''; # stuff after resource title not in link
819:
820: my $link = $params->{"resourceLink"};
821: my $src = $resource->src();
822: my $it = $params->{"iterator"};
823: my $filter = $it->{FILTER};
824:
825: my $title = $resource->compTitle();
826: if ($src =~ /^\/uploaded\//) {
827: $nonLinkedText=$title;
828: $title = '';
829: }
830: my $partLabel = "";
831: my $newBranchText = "";
832:
833: # If this is a new branch, label it so
834: if ($params->{'isNewBranch'}) {
835: $newBranchText = "<img src='/adm/lonIcons/branch.gif' border='0' />";
836: }
837:
838: # links to open and close the folder
839: my $linkopen = "<a href='$link'>";
840: my $linkclose = "</a>";
841:
842: # Default icon: HTML page
843: my $icon = "<img src='/adm/lonIcons/html.gif' alt='' border='0' />";
844:
845: if ($resource->is_problem()) {
846: if ($part eq '0' || $params->{'condensed'}) {
847: $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border="0" />';
848: } else {
849: $icon = $params->{'indentString'};
850: }
851: }
852:
853: # Display the correct map icon to open or shut map
854: if ($resource->is_map()) {
855: my $mapId = $resource->map_pc();
856: my $nowOpen = !defined($filter->{$mapId});
857: if ($it->{CONDITION}) {
858: $nowOpen = !$nowOpen;
859: }
860:
861: if (!$params->{'resource_no_folder_link'}) {
862: $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') . '.gif';
863: $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
864:
865: $linkopen = "<a href='" . $params->{'url'} . '?' .
866: $params->{'queryString'} . '&filter=';
867: $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
868: addToFilter($filter, $mapId) :
869: removeFromFilter($filter, $mapId);
870: $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
871: . $params->{'hereType'} . '&here=' .
872: &Apache::lonnet::escape($params->{'here'}) .
873: '&jump=' .
874: &Apache::lonnet::escape($resource->symb()) .
875: "&folderManip=1'>";
876: } else {
877: # Don't allow users to manipulate folder
878: $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') .
879: '.nomanip.gif';
880: $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
881:
882: $linkopen = "";
883: $linkclose = "";
884: }
885: }
886:
887: if ($resource->randomout()) {
888: $nonLinkedText .= ' <i>(hidden)</i> ';
889: }
890:
891: # We're done preparing and finally ready to start the rendering
892: my $result = "<td align='left' valign='center'>";
893:
894: my $indentLevel = $params->{'indentLevel'};
895: if ($newBranchText) { $indentLevel--; }
896:
897: # print indentation
898: for (my $i = 0; $i < $indentLevel; $i++) {
899: $result .= $params->{'indentString'};
900: }
901:
902: # Decide what to display
903: $result .= "$newBranchText$linkopen$icon$linkclose";
904:
905: my $curMarkerBegin = '';
906: my $curMarkerEnd = '';
907:
908: # Is this the current resource?
909: if (!$params->{'displayedHereMarker'} &&
910: $resource->symb() eq $params->{'here'} ) {
911: $curMarkerBegin = '<font color="red" size="+2">> </font>';
912: $curMarkerEnd = '<font color="red" size="+2"><</font>';
913: $params->{'displayedHereMarker'} = 1;
914: }
915:
916: if ($resource->is_problem() && $part ne '0' &&
917: !$params->{'condensed'}) {
918: $partLabel = " (Part $part)";
919: $title = "";
920: }
921:
922: if ($params->{'condensed'} && $resource->countParts() > 1) {
923: $nonLinkedText .= ' (' . $resource->countParts() . ' parts)';
924: }
925:
926: if (!$params->{'resource_nolink'}) {
927: $result .= " $curMarkerBegin<a href='$link'>$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
928: } else {
929: $result .= " $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
930: }
931:
932: return $result;
933: }
934:
935: sub render_communication_status {
936: my ($resource, $part, $params) = @_;
937: my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
938:
939: my $link = $params->{"resourceLink"};
940: my $linkopen = "<a href='$link'>";
941: my $linkclose = "</a>";
942:
943: if ($resource->hasDiscussion()) {
944: $discussionHTML = $linkopen .
945: '<img border="0" src="/adm/lonMisc/chat.gif" />' .
946: $linkclose;
947: }
948:
949: if ($resource->getFeedback()) {
950: my $feedback = $resource->getFeedback();
951: foreach (split(/\,/, $feedback)) {
952: if ($_) {
953: $feedbackHTML .= ' <a href="/adm/email?display='
954: . &Apache::lonnet::escape($_) . '">'
955: . '<img src="/adm/lonMisc/feedback.gif" '
956: . 'border="0" /></a>';
957: }
958: }
959: }
960:
961: if ($resource->getErrors()) {
962: my $errors = $resource->getErrors();
963: foreach (split(/,/, $errors)) {
964: if ($_) {
965: $errorHTML .= ' <a href="/adm/email?display='
966: . &Apache::lonnet::escape($_) . '">'
967: . '<img src="/adm/lonMisc/bomb.gif" '
968: . 'border="0" /></a>';
969: }
970: }
971: }
972:
973: if ($params->{'multipart'} && $part != '0') {
974: $discussionHTML = $feedbackHTML = $errorHTML = '';
975: }
976:
977: return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML </td>";
978:
979: }
980: sub render_quick_status {
981: my ($resource, $part, $params) = @_;
982: my $result = "";
983: my $firstDisplayed = !$params->{'condensed'} &&
984: $params->{'multipart'} && $part eq "0";
985:
986: my $link = $params->{"resourceLink"};
987: my $linkopen = "<a href='$link'>";
988: my $linkclose = "</a>";
989:
990: if ($resource->is_problem() &&
991: !$firstDisplayed) {
992: my $icon = $statusIconMap{$resource->status($part)};
993: my $alt = $iconAltTags{$icon};
994: if ($icon) {
995: $result .= "<td width='30' valign='center' width='50' align='right'>$linkopen<img width='25' height='25' src='/adm/lonIcons/$icon' border='0' alt='$alt' />$linkclose</td>\n";
996: } else {
997: $result .= "<td width='30'> </td>\n";
998: }
999: } else { # not problem, no icon
1000: $result .= "<td width='30'> </td>\n";
1001: }
1002:
1003: return $result;
1004: }
1005: sub render_long_status {
1006: my ($resource, $part, $params) = @_;
1007: my $result = "<td align='right' valign='center'>\n";
1008: my $firstDisplayed = !$params->{'condensed'} &&
1009: $params->{'multipart'} && $part eq "0";
1010:
1011: my $color;
1012: if ($resource->is_problem() && ($resource->countParts() <= 1 || $part ne '') ) {
1013: $color = $colormap{$resource->status};
1014:
1015: if (dueInLessThen24Hours($resource, $part) ||
1016: lastTry($resource, $part)) {
1017: $color = $hurryUpColor;
1018: }
1019: }
1020:
1021: if ($resource->kind() eq "res" &&
1022: $resource->is_problem() &&
1023: !$firstDisplayed) {
1024: if ($color) {$result .= "<font color=\"$color\"><b>"; }
1025: $result .= getDescription($resource, $part);
1026: if ($color) {$result .= "</b></font>"; }
1027: }
1028: if ($resource->is_map() && advancedUser() && $resource->randompick()) {
1029: $result .= '(randomly select ' . $resource->randompick() .')';
1030: }
1031:
1032: return $result;
1033: }
1034:
1035: my @preparedColumns = (\&render_resource, \&render_communication_status,
1036: \&render_quick_status, \&render_long_status);
1037:
1038: sub setDefault {
1039: my ($val, $default) = @_;
1040: if (!defined($val)) { return $default; }
1041: return $val;
1042: }
1043:
1044: sub render {
1045: my $args = shift;
1046: &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
1047: my $result = '';
1048:
1049: # Configure the renderer.
1050: my $cols = $args->{'cols'};
1051: if (!defined($cols)) {
1052: # no columns, no nav maps.
1053: return '';
1054: }
1055: my $mustCloseNavMap = 0;
1056: my $navmap;
1057: if (defined($args->{'navmap'})) {
1058: $navmap = $args->{'navmap'};
1059: }
1060:
1061: my $r = $args->{'r'};
1062: my $queryString = $args->{'queryString'};
1063: my $jump = $args->{'jump'};
1064: my $here = $args->{'here'};
1065: my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
1066: my $currentJumpDelta = 2; # change this to change how many resources are displayed
1067: # before the current resource when using #current
1068:
1069: # If we were passed 'here' information, we are not rendering
1070: # after a folder manipulation, and we were not passed an
1071: # iterator, make sure we open the folders to show the "here"
1072: # marker
1073: my $filterHash = {};
1074: # Figure out what we're not displaying
1075: foreach (split(/\,/, $ENV{"form.filter"})) {
1076: if ($_) {
1077: $filterHash->{$_} = "1";
1078: }
1079: }
1080:
1081: # Filter: Remember filter function and add our own filter: Refuse
1082: # to show hidden resources unless the user can see them.
1083: my $userCanSeeHidden = advancedUser();
1084: my $filterFunc = setDefault($args->{'filterFunc'},
1085: sub {return 1;});
1086: if (!$userCanSeeHidden) {
1087: # Without renaming the filterfunc, the server seems to go into
1088: # an infinite loop
1089: my $oldFilterFunc = $filterFunc;
1090: $filterFunc = sub { my $res = shift; return !$res->randomout() &&
1091: &$oldFilterFunc($res);};
1092: }
1093:
1094: my $condition = 0;
1095: if ($ENV{'form.condition'}) {
1096: $condition = 1;
1097: }
1098:
1099: if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
1100: # Step 1: Check to see if we have a navmap
1101: if (!defined($navmap)) {
1102: $navmap = Apache::lonnavmaps::navmap->new(
1103: $ENV{"request.course.fn"}.".db",
1104: $ENV{"request.course.fn"}."_parms.db", 1, 1);
1105: $mustCloseNavMap = 1;
1106: }
1107: $navmap->init();
1108:
1109: # Step two: Locate what kind of here marker is necessary
1110: # Determine where the "here" marker is and where the screen jumps to.
1111:
1112: if ($ENV{'form.postsymb'}) {
1113: $here = $jump = $ENV{'form.postsymb'};
1114: } elsif ($ENV{'form.postdata'}) {
1115: # couldn't find a symb, is there a URL?
1116: my $currenturl = $ENV{'form.postdata'};
1117: #$currenturl=~s/^http\:\/\///;
1118: #$currenturl=~s/^[^\/]+//;
1119:
1120: $here = $jump = &Apache::lonnet::symbread($currenturl);
1121: }
1122:
1123: # Step three: Ensure the folders are open
1124: my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
1125: my $depth = 1;
1126: $mapIterator->next(); # discard the first BEGIN_MAP
1127: my $curRes = $mapIterator->next();
1128: my $found = 0;
1129:
1130: # We only need to do this if we need to open the maps to show the
1131: # current position. This will change the counter so we can't count
1132: # for the jump marker with this loop.
1133: while ($depth > 0 && !$found) {
1134: if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
1135: if ($curRes == $mapIterator->END_MAP()) { $depth--; }
1136:
1137: if (ref($curRes) && $curRes->symb() eq $here) {
1138: my $mapStack = $mapIterator->getStack();
1139:
1140: # Ensure the parent maps are open
1141: for my $map (@{$mapStack}) {
1142: if ($condition) {
1143: undef $filterHash->{$map->map_pc()};
1144: } else {
1145: $filterHash->{$map->map_pc()} = 1;
1146: }
1147: }
1148: $found = 1;
1149: }
1150:
1151: $curRes = $mapIterator->next();
1152: }
1153: }
1154:
1155: if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
1156: # If this is a click on a folder or something, we want to preserve the "here"
1157: # from the querystring, and get the new "jump" marker
1158: $here = $ENV{'form.here'};
1159: $jump = $ENV{'form.jump'};
1160: }
1161:
1162: my $it = $args->{'iterator'};
1163: if (!defined($it)) {
1164: # Construct a default iterator based on $ENV{'form.'} information
1165:
1166: # Step 1: Check to see if we have a navmap
1167: if (!defined($navmap)) {
1168: $navmap = Apache::lonnavmaps::navmap->new($r,
1169: $ENV{"request.course.fn"}.".db",
1170: $ENV{"request.course.fn"}."_parms.db", 1, 1);
1171: $mustCloseNavMap = 1;
1172: }
1173: # Paranoia: Make sure it's ready
1174: $navmap->init();
1175:
1176: # See if we're being passed a specific map
1177: if ($args->{'iterator_map'}) {
1178: my $map = $args->{'iterator_map'};
1179: $map = $navmap->getResourceByUrl($map);
1180: my $firstResource = $map->map_start();
1181: my $finishResource = $map->map_finish();
1182:
1183: $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
1184: } else {
1185: $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
1186: }
1187: }
1188:
1189: # (re-)Locate the jump point, if any
1190: # Note this does not take filtering or hidden into account... need
1191: # to be fixed?
1192: my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
1193: my $depth = 1;
1194: $mapIterator->next();
1195: my $curRes = $mapIterator->next();
1196: my $foundJump = 0;
1197: my $counter = 0;
1198:
1199: while ($depth > 0 && !$foundJump) {
1200: if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
1201: if ($curRes == $mapIterator->END_MAP()) { $depth--; }
1202: if (ref($curRes)) { $counter++; }
1203:
1204: if (ref($curRes) && $jump eq $curRes->symb()) {
1205:
1206: # This is why we have to use the main iterator instead of the
1207: # potentially faster DFS: The count has to be the same, so
1208: # the order has to be the same, which DFS won't give us.
1209: $args->{'currentJumpIndex'} = $counter;
1210: $foundJump = 1;
1211: }
1212:
1213: $curRes = $mapIterator->next();
1214: }
1215:
1216: my $showParts = setDefault($args->{'showParts'}, 1);
1217: my $condenseParts = setDefault($args->{'condenseParts'}, 1);
1218: # keeps track of when the current resource is found,
1219: # so we can back up a few and put the anchor above the
1220: # current resource
1221: my $printKey = $args->{'printKey'};
1222: my $printCloseAll = $args->{'printCloseAll'};
1223: if (!defined($printCloseAll)) { $printCloseAll = 1; }
1224:
1225: # Print key?
1226: if ($printKey) {
1227: $result .= '<table border="0" cellpadding="2" cellspacing="0">';
1228: my $date=localtime;
1229: $result.='<tr><td align="right" valign="bottom">Key: </td>';
1230: if ($navmap->{LAST_CHECK}) {
1231: $result .=
1232: '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
1233: strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
1234: '</td><td align="center" valign="bottom"> '.
1235: '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
1236: '</td>';
1237: } else {
1238: $result .= '<td align="center" valign="bottom"> '.
1239: '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
1240: ' <img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
1241: '</td>';
1242: }
1243:
1244: $result .= '</tr></table>';
1245: }
1246:
1247: if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
1248: if ($condition) {
1249: $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
1250: "&here=" . Apache::lonnet::escape($here) .
1251: "\">Close All Folders</a>";
1252: } else {
1253: $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
1254: "&here=" . Apache::lonnet::escape($here) .
1255: "\">Open All Folders</a>";
1256: }
1257: $result .= "<br /><br />\n";
1258: }
1259:
1260: if ($r) {
1261: $r->print($result);
1262: $r->rflush();
1263: $result = "";
1264: }
1265: # End parameter setting
1266:
1267: # Data
1268: $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
1269: my $res = "Apache::lonnavmaps::resource";
1270: my %condenseStatuses =
1271: ( $res->NETWORK_FAILURE => 1,
1272: $res->NOTHING_SET => 1,
1273: $res->CORRECT => 1 );
1274: my @backgroundColors = ("#FFFFFF", "#F6F6F6");
1275:
1276: # Shared variables
1277: $args->{'counter'} = 0; # counts the rows
1278: $args->{'indentLevel'} = 0;
1279: $args->{'isNewBranch'} = 0;
1280: $args->{'condensed'} = 0;
1281: $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
1282: $args->{'displayedHereMarker'} = 0;
1283:
1284: # If we're suppressing empty sequences, look for them here. Use DFS for speed,
1285: # since structure actually doesn't matter, except what map has what resources.
1286: if ($args->{'suppressEmptySequences'}) {
1287: my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
1288: $it->{FIRST_RESOURCE},
1289: $it->{FINISH_RESOURCE},
1290: {}, undef, 1);
1291: $depth = 0;
1292: $dfsit->next();
1293: my $curRes = $dfsit->next();
1294: while ($depth > -1) {
1295: if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
1296: if ($curRes == $dfsit->END_MAP()) { $depth--; }
1297:
1298: if (ref($curRes)) {
1299: # Parallel pre-processing: Do sequences have non-filtered-out children?
1300: if ($curRes->is_map()) {
1301: $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
1302: # Sequences themselves do not count as visible children,
1303: # unless those sequences also have visible children.
1304: # This means if a sequence appears, there's a "promise"
1305: # that there's something under it if you open it, somewhere.
1306: } else {
1307: # Not a sequence: if it's filtered, ignore it, otherwise
1308: # rise up the stack and mark the sequences as having children
1309: if (&$filterFunc($curRes)) {
1310: for my $sequence (@{$dfsit->getStack()}) {
1311: $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
1312: }
1313: }
1314: }
1315: }
1316: } continue {
1317: $curRes = $dfsit->next();
1318: }
1319: }
1320:
1321: my $displayedJumpMarker = 0;
1322: # Set up iteration.
1323: $depth = 1;
1324: $it->next(); # discard initial BEGIN_MAP
1325: $curRes = $it->next();
1326: my $now = time();
1327: my $in24Hours = $now + 24 * 60 * 60;
1328: my $rownum = 0;
1329:
1330: # export "here" marker information
1331: $args->{'here'} = $here;
1332:
1333: while ($depth > 0) {
1334: if ($curRes == $it->BEGIN_MAP()) { $depth++; }
1335: if ($curRes == $it->END_MAP()) { $depth--; }
1336:
1337: # Maintain indentation level.
1338: if ($curRes == $it->BEGIN_MAP() ||
1339: $curRes == $it->BEGIN_BRANCH() ) {
1340: $args->{'indentLevel'}++;
1341: }
1342: if ($curRes == $it->END_MAP() ||
1343: $curRes == $it->END_BRANCH() ) {
1344: $args->{'indentLevel'}--;
1345: }
1346: # Notice new branches
1347: if ($curRes == $it->BEGIN_BRANCH()) {
1348: $args->{'isNewBranch'} = 1;
1349: }
1350:
1351: # If this isn't an actual resource, continue on
1352: if (!ref($curRes)) {
1353: next;
1354: }
1355:
1356: # If this has been filtered out, continue on
1357: if (!(&$filterFunc($curRes))) {
1358: $args->{'isNewBranch'} = 0; # Don't falsely remember this
1359: next;
1360: }
1361:
1362: # If this is an empty sequence and we're filtering them, continue on
1363: if ($curRes->is_map() && $args->{'suppressEmptySequences'} &&
1364: !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) {
1365: next;
1366: }
1367:
1368: # If we're suppressing navmaps and this is a navmap, continue on
1369: if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
1370: next;
1371: }
1372:
1373: $args->{'counter'}++;
1374:
1375: # Does it have multiple parts?
1376: $args->{'multipart'} = 0;
1377: $args->{'condensed'} = 0;
1378: my @parts;
1379:
1380: # Decide what parts to show.
1381: if ($curRes->is_problem() && $showParts) {
1382: @parts = @{$curRes->parts()};
1383: $args->{'multipart'} = $curRes->multipart();
1384:
1385: if ($condenseParts) { # do the condensation
1386: if (!$curRes->opendate("0")) {
1387: @parts = ();
1388: $args->{'condensed'} = 1;
1389: }
1390: if (!$args->{'condensed'}) {
1391: # Decide whether to condense based on similarity
1392: my $status = $curRes->status($parts[0]);
1393: my $due = $curRes->duedate($parts[0]);
1394: my $open = $curRes->opendate($parts[0]);
1395: my $statusAllSame = 1;
1396: my $dueAllSame = 1;
1397: my $openAllSame = 1;
1398: for (my $i = 1; $i < scalar(@parts); $i++) {
1399: if ($curRes->status($parts[$i]) != $status){
1400: $statusAllSame = 0;
1401: }
1402: if ($curRes->duedate($parts[$i]) != $due ) {
1403: $dueAllSame = 0;
1404: }
1405: if ($curRes->opendate($parts[$i]) != $open) {
1406: $openAllSame = 0;
1407: }
1408: }
1409: # $*allSame is true if all the statuses were
1410: # the same. Now, if they are all the same and
1411: # match one of the statuses to condense, or they
1412: # are all open with the same due date, or they are
1413: # all OPEN_LATER with the same open date, display the
1414: # status of the first non-zero part (to get the 'correct'
1415: # status right, since 0 is never 'correct' or 'open').
1416: if (($statusAllSame && defined($condenseStatuses{$status})) ||
1417: ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
1418: ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
1419: @parts = ($parts[0]);
1420: $args->{'condensed'} = 1;
1421: }
1422: }
1423: # Multipart problem with one part: always "condense" (happens
1424: # to match the desirable behavior)
1425: if ($curRes->countParts() == 1) {
1426: @parts = ($parts[0]);
1427: $args->{'condensed'} = 1;
1428: }
1429: }
1430: }
1431:
1432: # If the multipart problem was condensed, "forget" it was multipart
1433: if (scalar(@parts) == 1) {
1434: $args->{'multipart'} = 0;
1435: } else {
1436: # Add part 0 so we display it correctly.
1437: unshift @parts, '0';
1438: }
1439:
1440: # Now, we've decided what parts to show. Loop through them and
1441: # show them.
1442: foreach my $part (@parts) {
1443: $rownum ++;
1444: my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
1445:
1446: $result .= " <tr bgcolor='$backgroundColor'>\n";
1447:
1448: # Set up some data about the parts that the cols might want
1449: my $filter = $it->{FILTER};
1450: my $stack = $it->getStack();
1451: my $src = getLinkForResource($stack);
1452:
1453: my $srcHasQuestion = $src =~ /\?/;
1454: $args->{"resourceLink"} = $src.
1455: ($srcHasQuestion?'&':'?') .
1456: 'symb=' . &Apache::lonnet::escape($curRes->symb());
1457:
1458: # Now, display each column.
1459: foreach my $col (@$cols) {
1460: my $colHTML = '';
1461: if (ref($col)) {
1462: $colHTML .= &$col($curRes, $part, $args);
1463: } else {
1464: $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
1465: }
1466:
1467: # If this is the first column and it's time to print
1468: # the anchor, do so
1469: if ($col == $cols->[0] &&
1470: $args->{'counter'} == $args->{'currentJumpIndex'} -
1471: $currentJumpDelta) {
1472: # Jam the anchor after the <td> tag;
1473: # necessary for valid HTML (which Mozilla requires)
1474: $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
1475: $displayedJumpMarker = 1;
1476: }
1477: $result .= $colHTML . "\n";
1478: }
1479: $result .= " </tr>\n";
1480: $args->{'isNewBranch'} = 0;
1481: }
1482:
1483: if ($r && $rownum % 20 == 0) {
1484: $r->print($result);
1485: $result = "";
1486: $r->rflush();
1487: }
1488: } continue {
1489: $curRes = $it->next();
1490: }
1491:
1492: # Print out the part that jumps to #curloc if it exists
1493: # delay needed because the browser is processing the jump before
1494: # it finishes rendering, so it goes to the wrong place!
1495: # onload might be better, but this routine has no access to that.
1496: # On mozilla, the 0-millisecond timeout seems to prevent this;
1497: # it's quite likely this might fix other browsers, too, and
1498: # certainly won't hurt anything.
1499: if ($displayedJumpMarker) {
1500: $result .= "<script>setTimeout(\"location += '#curloc';\", 0)</script>\n";
1501: }
1502:
1503: $result .= "</table>";
1504:
1505: if ($r) {
1506: $r->print($result);
1507: $result = "";
1508: $r->rflush();
1509: }
1510:
1511: if ($mustCloseNavMap) { $navmap->untieHashes(); }
1512:
1513: return $result;
1514: }
1515:
1516: 1;
1517:
1518: package Apache::lonnavmaps::navmap;
1519:
1520: =pod
1521:
1522: lonnavmaps provides functions and objects for dealing with the
1523: compiled course hashes generated when a user enters the course, the
1524: Apache handler for the "Navigation Map" button, and a flexible
1525: prepared renderer for navigation maps that are easy to use anywhere.
1526:
1527: =head1 Object: navmap
1528:
1529: Encapsulating the compiled nav map
1530:
1531: navmap is an object that encapsulates a compiled course map and
1532: provides a reasonable interface to it.
1533:
1534: Most notably it provides a way to navigate the map sensibly and a
1535: flexible iterator that makes it easy to write various renderers based
1536: on nav maps.
1537:
1538: You must obtain resource objects through the navmap object.
1539:
1540: =head2 Methods
1541:
1542: =over 4
1543:
1544: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions,
1545: genMailDiscussStatus):
1546:
1547: Binds a new navmap object to the compiled nav map hash and parm hash
1548: given as filenames. genCourseAndUserOptions is a flag saying whether
1549: the course options and user options hash should be generated. This is
1550: for when you are using the parameters of the resources that require
1551: them; see documentation in resource object
1552: documentation. genMailDiscussStatus causes the nav map to retreive
1553: information about the email and discussion status of
1554: resources. Returns the navmap object if this is successful, or
1555: B<undef> if not. You must check for undef; errors will occur when you
1556: try to use the other methods otherwise.
1557:
1558: =item * B<getIterator>(first, finish, filter, condition):
1559:
1560: See iterator documentation below.
1561:
1562: =cut
1563:
1564: use strict;
1565: use GDBM_File;
1566:
1567: sub new {
1568: # magic invocation to create a class instance
1569: my $proto = shift;
1570: my $class = ref($proto) || $proto;
1571: my $self = {};
1572:
1573: $self->{NAV_HASH_FILE} = shift;
1574: $self->{PARM_HASH_FILE} = shift;
1575: $self->{GENERATE_COURSE_USER_OPT} = shift;
1576: $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
1577:
1578: # Resource cache stores navmap resources as we reference them. We generate
1579: # them on-demand so we don't pay for creating resources unless we use them.
1580: $self->{RESOURCE_CACHE} = {};
1581:
1582: # Network failure flag, if we accessed the course or user opt and
1583: # failed
1584: $self->{NETWORK_FAILURE} = 0;
1585:
1586: # tie the nav hash
1587:
1588: my %navmaphash;
1589: my %parmhash;
1590: if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
1591: &GDBM_READER(), 0640))) {
1592: return undef;
1593: }
1594:
1595: if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
1596: &GDBM_READER(), 0640)))
1597: {
1598: untie %{$self->{PARM_HASH}};
1599: return undef;
1600: }
1601:
1602: $self->{NAV_HASH} = \%navmaphash;
1603: $self->{PARM_HASH} = \%parmhash;
1604: $self->{INITED} = 0;
1605:
1606: bless($self);
1607:
1608: return $self;
1609: }
1610:
1611: sub init {
1612: my $self = shift;
1613: if ($self->{INITED}) { return; }
1614:
1615: # If the course opt hash and the user opt hash should be generated,
1616: # generate them
1617: if ($self->{GENERATE_COURSE_USER_OPT}) {
1618: my $uname=$ENV{'user.name'};
1619: my $udom=$ENV{'user.domain'};
1620: my $uhome=$ENV{'user.home'};
1621: my $cid=$ENV{'request.course.id'};
1622: my $chome=$ENV{'course.'.$cid.'.home'};
1623: my ($cdom,$cnum)=split(/\_/,$cid);
1624:
1625: my $userprefix=$uname.'_'.$udom.'_';
1626:
1627: my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
1628: unless ($uhome eq 'no_host') {
1629: # ------------------------------------------------- Get coursedata (if present)
1630: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
1631: my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
1632: ':resourcedata',$chome);
1633: # Check for network failure
1634: if ( $reply =~ /no.such.host/i || $reply =~ /con_lost/i) {
1635: $self->{NETWORK_FAILURE} = 1;
1636: } elsif ($reply!~/^error\:/) {
1637: $courserdatas{$cid}=$reply;
1638: $courserdatas{$cid.'.last_cache'}=time;
1639: }
1640: }
1641: foreach (split(/\&/,$courserdatas{$cid})) {
1642: my ($name,$value)=split(/\=/,$_);
1643: $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
1644: &Apache::lonnet::unescape($value);
1645: }
1646: # --------------------------------------------------- Get userdata (if present)
1647: unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
1648: my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
1649: if ($reply!~/^error\:/) {
1650: $userrdatas{$uname.'___'.$udom}=$reply;
1651: $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
1652: }
1653: # check to see if network failed
1654: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
1655: {
1656: $self->{NETWORK_FAILURE} = 1;
1657: }
1658: }
1659: foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
1660: my ($name,$value)=split(/\=/,$_);
1661: $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
1662: &Apache::lonnet::unescape($value);
1663: }
1664: $self->{COURSE_OPT} = \%courseopt;
1665: $self->{USER_OPT} = \%useropt;
1666: }
1667: }
1668:
1669: if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
1670: my $cid=$ENV{'request.course.id'};
1671: my ($cdom,$cnum)=split(/\_/,$cid);
1672:
1673: my %emailstatus = &Apache::lonnet::dump('email_status');
1674: my $logoutTime = $emailstatus{'logout'};
1675: my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
1676: $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
1677: $courseLeaveTime : $logoutTime);
1678: my %discussiontime = &Apache::lonnet::dump('discussiontimes',
1679: $cdom, $cnum);
1680: my %feedback=();
1681: my %error=();
1682: my $keys = &Apache::lonnet::reply('keys:'.
1683: $ENV{'user.domain'}.':'.
1684: $ENV{'user.name'}.':nohist_email',
1685: $ENV{'user.home'});
1686:
1687: foreach my $msgid (split(/\&/, $keys)) {
1688: $msgid=&Apache::lonnet::unescape($msgid);
1689: my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
1690: if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
1691: my ($what,$url)=($1,$2);
1692: my %status=
1693: &Apache::lonnet::get('email_status',[$msgid]);
1694: if ($status{$msgid}=~/^error\:/) {
1695: $status{$msgid}='';
1696: }
1697:
1698: if (($status{$msgid} eq 'new') ||
1699: (!$status{$msgid})) {
1700: if ($what eq 'Error') {
1701: $error{$url}.=','.$msgid;
1702: } else {
1703: $feedback{$url}.=','.$msgid;
1704: }
1705: }
1706: }
1707: }
1708:
1709: $self->{FEEDBACK} = \%feedback;
1710: $self->{ERROR_MSG} = \%error; # what is this? JB
1711: $self->{DISCUSSION_TIME} = \%discussiontime;
1712: $self->{EMAIL_STATUS} = \%emailstatus;
1713:
1714: }
1715:
1716: $self->{PARM_CACHE} = {};
1717: $self->{INITED} = 1;
1718: }
1719:
1720: # Internal function: Takes a key to look up in the nav hash and implements internal
1721: # memory caching of that key.
1722: sub navhash {
1723: my $self = shift; my $key = shift;
1724: return $self->{NAV_HASH}->{$key};
1725: }
1726:
1727: # Checks to see if coursemap is defined, matching test in old lonnavmaps
1728: sub courseMapDefined {
1729: my $self = shift;
1730: my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
1731:
1732: my $firstres = $self->navhash("map_start_$uri");
1733: my $lastres = $self->navhash("map_finish_$uri");
1734: return $firstres && $lastres;
1735: }
1736:
1737: sub getIterator {
1738: my $self = shift;
1739: my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
1740: shift, undef, shift);
1741: return $iterator;
1742: }
1743:
1744: # unties the hash when done
1745: sub untieHashes {
1746: my $self = shift;
1747: untie %{$self->{NAV_HASH}};
1748: untie %{$self->{PARM_HASH}};
1749: }
1750:
1751: # Private method: Does the given resource (as a symb string) have
1752: # current discussion? Returns 0 if chat/mail data not extracted.
1753: sub hasDiscussion {
1754: my $self = shift;
1755: my $symb = shift;
1756: if (!defined($self->{DISCUSSION_TIME})) { return 0; }
1757:
1758: #return defined($self->{DISCUSSION_TIME}->{$symb});
1759: return $self->{DISCUSSION_TIME}->{$symb} >
1760: $self->{LAST_CHECK};
1761: }
1762:
1763: # Private method: Does the given resource (as a symb string) have
1764: # current feedback? Returns the string in the feedback hash, which
1765: # will be false if it does not exist.
1766: sub getFeedback {
1767: my $self = shift;
1768: my $symb = shift;
1769:
1770: if (!defined($self->{FEEDBACK})) { return ""; }
1771:
1772: return $self->{FEEDBACK}->{$symb};
1773: }
1774:
1775: # Private method: Get the errors for that resource (by source).
1776: sub getErrors {
1777: my $self = shift;
1778: my $src = shift;
1779:
1780: if (!defined($self->{ERROR_MSG})) { return ""; }
1781: return $self->{ERROR_MSG}->{$src};
1782: }
1783:
1784: =pod
1785:
1786: =item * B<getById>(id):
1787:
1788: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
1789: object for that resource. This method, or other methods that use it
1790: (as in the resource object) is the only proper way to obtain a
1791: resource object.
1792:
1793: =item * B<getBySymb>(symb):
1794:
1795: Based on the symb of the resource, get a resource object for that
1796: resource. This is one of the proper ways to get a resource object.
1797:
1798: =item * B<getMapByMapPc>(map_pc):
1799:
1800: Based on the map_pc of the resource, get a resource object for
1801: the given map. This is one of the proper ways to get a resource object.
1802:
1803: =cut
1804:
1805: # The strategy here is to cache the resource objects, and only construct them
1806: # as we use them. The real point is to prevent reading any more from the tied
1807: # hash then we have to, which should hopefully alleviate speed problems.
1808: # Caching is just an incidental detail I throw in because it makes sense.
1809:
1810: sub getById {
1811: my $self = shift;
1812: my $id = shift;
1813:
1814: if (defined ($self->{RESOURCE_CACHE}->{$id}))
1815: {
1816: return $self->{RESOURCE_CACHE}->{$id};
1817: }
1818:
1819: # resource handles inserting itself into cache.
1820: # Not clear why the quotes are necessary, but as of this
1821: # writing it doesn't work without them.
1822: return "Apache::lonnavmaps::resource"->new($self, $id);
1823: }
1824:
1825: sub getBySymb {
1826: my $self = shift;
1827: my $symb = shift;
1828: my ($mapUrl, $id, $filename) = split (/___/, $symb);
1829: my $map = $self->getResourceByUrl($mapUrl);
1830: return $self->getById($map->map_pc() . '.' . $id);
1831: }
1832:
1833: sub getByMapPc {
1834: my $self = shift;
1835: my $map_pc = shift;
1836: my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
1837: $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
1838: return $self->getById($map_id);
1839: }
1840:
1841: =pod
1842:
1843: =item * B<firstResource>():
1844:
1845: Returns a resource object reference corresponding to the first
1846: resource in the navmap.
1847:
1848: =cut
1849:
1850: sub firstResource {
1851: my $self = shift;
1852: my $firstResource = $self->navhash('map_start_' .
1853: &Apache::lonnet::clutter($ENV{'request.course.uri'}));
1854: return $self->getById($firstResource);
1855: }
1856:
1857: =pod
1858:
1859: =item * B<finishResource>():
1860:
1861: Returns a resource object reference corresponding to the last resource
1862: in the navmap.
1863:
1864: =cut
1865:
1866: sub finishResource {
1867: my $self = shift;
1868: my $firstResource = $self->navhash('map_finish_' .
1869: &Apache::lonnet::clutter($ENV{'request.course.uri'}));
1870: return $self->getById($firstResource);
1871: }
1872:
1873: # Parmval reads the parm hash and cascades the lookups. parmval_real does
1874: # the actual lookup; parmval caches the results.
1875: sub parmval {
1876: my $self = shift;
1877: my ($what,$symb)=@_;
1878: my $hashkey = $what."|||".$symb;
1879:
1880: if (defined($self->{PARM_CACHE}->{$hashkey})) {
1881: return $self->{PARM_CACHE}->{$hashkey};
1882: }
1883:
1884: my $result = $self->parmval_real($what, $symb);
1885: $self->{PARM_CACHE}->{$hashkey} = $result;
1886: return $result;
1887: }
1888:
1889: sub parmval_real {
1890: my $self = shift;
1891: my ($what,$symb) = @_;
1892:
1893: my $cid=$ENV{'request.course.id'};
1894: my $csec=$ENV{'request.course.sec'};
1895: my $uname=$ENV{'user.name'};
1896: my $udom=$ENV{'user.domain'};
1897:
1898: unless ($symb) { return ''; }
1899: my $result='';
1900:
1901: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
1902:
1903: # ----------------------------------------------------- Cascading lookup scheme
1904: my $rwhat=$what;
1905: $what=~s/^parameter\_//;
1906: $what=~s/\_/\./;
1907:
1908: my $symbparm=$symb.'.'.$what;
1909: my $mapparm=$mapname.'___(all).'.$what;
1910: my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
1911:
1912: my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
1913: my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
1914: my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
1915:
1916: my $courselevel= $usercourseprefix.'.'.$what;
1917: my $courselevelr=$usercourseprefix.'.'.$symbparm;
1918: my $courselevelm=$usercourseprefix.'.'.$mapparm;
1919:
1920: my $useropt = $self->{USER_OPT};
1921: my $courseopt = $self->{COURSE_OPT};
1922: my $parmhash = $self->{PARM_HASH};
1923:
1924: # ---------------------------------------------------------- first, check user
1925: if ($uname and defined($useropt)) {
1926: if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
1927: if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
1928: if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
1929: }
1930:
1931: # ------------------------------------------------------- second, check course
1932: if ($csec and defined($courseopt)) {
1933: if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
1934: if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
1935: if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
1936: }
1937:
1938: if (defined($courseopt)) {
1939: if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
1940: if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
1941: if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
1942: }
1943:
1944: # ----------------------------------------------------- third, check map parms
1945:
1946: my $thisparm=$$parmhash{$symbparm};
1947: if (defined($thisparm)) { return $thisparm; }
1948:
1949: # ----------------------------------------------------- fourth , check default
1950:
1951: my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
1952: if (defined($default)) { return $default}
1953:
1954: # --------------------------------------------------- fifth , cascade up parts
1955:
1956: my ($space,@qualifier)=split(/\./,$rwhat);
1957: my $qualifier=join('.',@qualifier);
1958: unless ($space eq '0') {
1959: my @parts=split(/_/,$space);
1960: my $id=pop(@parts);
1961: my $part=join('_',@parts);
1962: if ($part eq '') { $part='0'; }
1963: my $partgeneral=$self->parmval($part.".$qualifier",$symb);
1964: if (defined($partgeneral)) { return $partgeneral; }
1965: }
1966: return '';
1967: }
1968:
1969: =pod
1970:
1971: =item * B<getResourceByUrl>(url):
1972:
1973: Retrieves a resource object by URL of the resource. If passed a
1974: resource object, it will simply return it, so it is safe to use this
1975: method in code like "$res = $navmap->getResourceByUrl($res)", if
1976: you're not sure if $res is already an object, or just a URL. If the
1977: resource appears multiple times in the course, only the first instance
1978: will be returned. As a result, this is probably useful only for maps.
1979:
1980: =item * B<retrieveResources>(map, filterFunc, recursive, bailout):
1981:
1982: The map is a specification of a map to retreive the resources from,
1983: either as a url or as an object. The filterFunc is a reference to a
1984: function that takes a resource object as its one argument and returns
1985: true if the resource should be included, or false if it should not
1986: be. If recursive is true, the map will be recursively examined,
1987: otherwise it will not be. If bailout is true, the function will return
1988: as soon as it finds a resource, if false it will finish. By default,
1989: the map is the top-level map of the course, filterFunc is a function
1990: that always returns 1, recursive is true, bailout is false. The
1991: resources will be returned in a list containing the resource objects
1992: for the corresponding resources, with B<no structure information> in
1993: the list; regardless of branching, recursion, etc., it will be a flat
1994: list.
1995:
1996: Thus, this is suitable for cases where you don't want the structure,
1997: just a list of all resources. It is also suitable for finding out how
1998: many resources match a given description; for this use, if all you
1999: want to know is if I<any> resources match the description, the bailout
2000: parameter will allow you to avoid potentially expensive enumeration of
2001: all matching resources.
2002:
2003: =item * B<hasResources>(map, filterFunc, recursive):
2004:
2005: Convience method for
2006:
2007: scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
2008:
2009: which will tell whether the map has resources matching the description
2010: in the filter function.
2011:
2012: =cut
2013:
2014: sub getResourceByUrl {
2015: my $self = shift;
2016: my $resUrl = shift;
2017:
2018: if (ref($resUrl)) { return $resUrl; }
2019:
2020: $resUrl = &Apache::lonnet::clutter($resUrl);
2021: my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
2022: if ($resId =~ /,/) {
2023: $resId = (split (/,/, $resId))[0];
2024: }
2025: if (!$resId) { return ''; }
2026: return $self->getById($resId);
2027: }
2028:
2029: sub retrieveResources {
2030: my $self = shift;
2031: my $map = shift;
2032: my $filterFunc = shift;
2033: if (!defined ($filterFunc)) {
2034: $filterFunc = sub {return 1;};
2035: }
2036: my $recursive = shift;
2037: if (!defined($recursive)) { $recursive = 1; }
2038: my $bailout = shift;
2039: if (!defined($bailout)) { $bailout = 0; }
2040:
2041: # Create the necessary iterator.
2042: if (!ref($map)) { # assume it's a url of a map.
2043: $map = $self->getResourceByUrl($map);
2044: }
2045:
2046: # Check the map's validity.
2047: if (!$map || !$map->is_map()) {
2048: # Oh, to throw an exception.... how I'd love that!
2049: return ();
2050: }
2051:
2052: # Get an iterator.
2053: my $it = $self->getIterator($map->map_start(), $map->map_finish(),
2054: !$recursive);
2055:
2056: my @resources = ();
2057:
2058: # Run down the iterator and collect the resources.
2059: my $depth = 1;
2060: $it->next();
2061: my $curRes = $it->next();
2062:
2063: while ($depth > 0) {
2064: if ($curRes == $it->BEGIN_MAP()) {
2065: $depth++;
2066: }
2067: if ($curRes == $it->END_MAP()) {
2068: $depth--;
2069: }
2070:
2071: if (ref($curRes)) {
2072: if (!&$filterFunc($curRes)) {
2073: next;
2074: }
2075:
2076: push @resources, $curRes;
2077:
2078: if ($bailout) {
2079: return @resources;
2080: }
2081: }
2082:
2083: $curRes = $it->next();
2084: }
2085:
2086: return @resources;
2087: }
2088:
2089: sub hasResource {
2090: my $self = shift;
2091: my $map = shift;
2092: my $filterFunc = shift;
2093: my $recursive = shift;
2094:
2095: return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
2096: }
2097:
2098: 1;
2099:
2100: package Apache::lonnavmaps::iterator;
2101:
2102: =pod
2103:
2104: =back
2105:
2106: =head1 Object: navmap Iterator
2107:
2108: An I<iterator> encapsulates the logic required to traverse a data
2109: structure. navmap uses an iterator to traverse the course map
2110: according to the criteria you wish to use.
2111:
2112: To obtain an iterator, call the B<getIterator>() function of a
2113: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
2114: directly.) This will return a reference to the iterator:
2115:
2116: C<my $resourceIterator = $navmap-E<gt>getIterator();>
2117:
2118: To get the next thing from the iterator, call B<next>:
2119:
2120: C<my $nextThing = $resourceIterator-E<gt>next()>
2121:
2122: getIterator behaves as follows:
2123:
2124: =over 4
2125:
2126: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
2127:
2128: All parameters are optional. firstResource is a resource reference
2129: corresponding to where the iterator should start. It defaults to
2130: navmap->firstResource() for the corresponding nav map. finishResource
2131: corresponds to where you want the iterator to end, defaulting to
2132: navmap->finishResource(). filterHash is a hash used as a set
2133: containing strings representing the resource IDs, defaulting to
2134: empty. Condition is a 1 or 0 that sets what to do with the filter
2135: hash: If a 0, then only resource that exist IN the filterHash will be
2136: recursed on. If it is a 1, only resources NOT in the filterHash will
2137: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
2138: false (default), the iterator will only return the first level of map
2139: that is not just a single, 'redirecting' map. If true, the iterator
2140: will return all information, starting with the top-level map,
2141: regardless of content. returnTopMap, if true (default false), will
2142: cause the iterator to return the top-level map object (resource 0.0)
2143: before anything else.
2144:
2145: Thus, by default, only top-level resources will be shown. Change the
2146: condition to a 1 without changing the hash, and all resources will be
2147: shown. Changing the condition to 1 and including some values in the
2148: hash will allow you to selectively suppress parts of the navmap, while
2149: leaving it on 0 and adding things to the hash will allow you to
2150: selectively add parts of the nav map. See the handler code for
2151: examples.
2152:
2153: The iterator will return either a reference to a resource object, or a
2154: token representing something in the map, such as the beginning of a
2155: new branch. The possible tokens are:
2156:
2157: =over 4
2158:
2159: =item * BEGIN_MAP:
2160:
2161: A new map is being recursed into. This is returned I<after> the map
2162: resource itself is returned.
2163:
2164: =item * END_MAP:
2165:
2166: The map is now done.
2167:
2168: =item * BEGIN_BRANCH:
2169:
2170: A branch is now starting. The next resource returned will be the first
2171: in that branch.
2172:
2173: =item * END_BRANCH:
2174:
2175: The branch is now done.
2176:
2177: =back
2178:
2179: The tokens are retreivable via methods on the iterator object, i.e.,
2180: $iterator->END_MAP.
2181:
2182: Maps can contain empty resources. The iterator will automatically skip
2183: over such resources, but will still treat the structure
2184: correctly. Thus, a complicated map with several branches, but
2185: consisting entirely of empty resources except for one beginning or
2186: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
2187: but only one resource will be returned.
2188:
2189: =back
2190:
2191: =cut
2192:
2193: # Here are the tokens for the iterator:
2194:
2195: sub BEGIN_MAP { return 1; } # begining of a new map
2196: sub END_MAP { return 2; } # end of the map
2197: sub BEGIN_BRANCH { return 3; } # beginning of a branch
2198: sub END_BRANCH { return 4; } # end of a branch
2199: sub FORWARD { return 1; } # go forward
2200: sub BACKWARD { return 2; }
2201:
2202: sub min {
2203: (my $a, my $b) = @_;
2204: if ($a < $b) { return $a; } else { return $b; }
2205: }
2206:
2207: # In the CVS repository, documentation of this algorithm is included
2208: # in /doc/lonnavdocs, as a PDF and .tex source. Markers like **1**
2209: # will reference the same location in the text as the part of the
2210: # algorithm is running through.
2211:
2212: sub new {
2213: # magic invocation to create a class instance
2214: my $proto = shift;
2215: my $class = ref($proto) || $proto;
2216: my $self = {};
2217:
2218: $self->{NAV_MAP} = shift;
2219: return undef unless ($self->{NAV_MAP});
2220:
2221: # Handle the parameters
2222: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
2223: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
2224:
2225: # If the given resources are just the ID of the resource, get the
2226: # objects
2227: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
2228: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
2229: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
2230: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
2231:
2232: $self->{FILTER} = shift;
2233:
2234: # A hash, used as a set, of resource already seen
2235: $self->{ALREADY_SEEN} = shift;
2236: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
2237: $self->{CONDITION} = shift;
2238:
2239: # Do we want to automatically follow "redirection" maps?
2240: $self->{FORCE_TOP} = shift;
2241:
2242: # Do we want to return the top-level map object (resource 0.0)?
2243: $self->{RETURN_0} = shift;
2244: # have we done that yet?
2245: $self->{HAVE_RETURNED_0} = 0;
2246:
2247: # Now, we need to pre-process the map, by walking forward and backward
2248: # over the parts of the map we're going to look at.
2249:
2250: # The processing steps are exactly the same, except for a few small
2251: # changes, so I bundle those up in the following list of two elements:
2252: # (direction_to_iterate, VAL_name, next_resource_method_to_call,
2253: # first_resource).
2254: # This prevents writing nearly-identical code twice.
2255: my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext',
2256: 'FIRST_RESOURCE'],
2257: [BACKWARD(), 'BOT_UP_VAL', 'getPrevious',
2258: 'FINISH_RESOURCE'] );
2259:
2260: my $maxDepth = 0; # tracks max depth
2261:
2262: # If there is only one resource in this map, and it's a map, we
2263: # want to remember that, so the user can ask for the first map
2264: # that isn't just a redirector.
2265: my $resource; my $resourceCount = 0;
2266:
2267: # **1**
2268:
2269: foreach my $pass (@iterations) {
2270: my $direction = $pass->[0];
2271: my $valName = $pass->[1];
2272: my $nextResourceMethod = $pass->[2];
2273: my $firstResourceName = $pass->[3];
2274:
2275: my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP},
2276: $self->{FIRST_RESOURCE},
2277: $self->{FINISH_RESOURCE},
2278: {}, undef, 0, $direction);
2279:
2280: # prime the recursion
2281: $self->{$firstResourceName}->{DATA}->{$valName} = 0;
2282: my $depth = 0;
2283: $iterator->next();
2284: my $curRes = $iterator->next();
2285: while ($depth > -1) {
2286: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
2287: if ($curRes == $iterator->END_MAP()) { $depth--; }
2288:
2289: if (ref($curRes)) {
2290: # If there's only one resource, this will save it
2291: # we have to filter empty resources from consideration here,
2292: # or even "empty", redirecting maps have two (start & finish)
2293: # or three (start, finish, plus redirector)
2294: if($direction == FORWARD && $curRes->src()) {
2295: $resource = $curRes; $resourceCount++;
2296: }
2297: my $resultingVal = $curRes->{DATA}->{$valName};
2298: my $nextResources = $curRes->$nextResourceMethod();
2299: my $nextCount = scalar(@{$nextResources});
2300:
2301: if ($nextCount == 1) { # **3**
2302: my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
2303: $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
2304: }
2305:
2306: if ($nextCount > 1) { # **4**
2307: foreach my $res (@{$nextResources}) {
2308: my $current = $res->{DATA}->{$valName} || 999999999;
2309: $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
2310: }
2311: }
2312: }
2313:
2314: # Assign the final val (**2**)
2315: if (ref($curRes) && $direction == BACKWARD()) {
2316: my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
2317: $curRes->{DATA}->{BOT_UP_VAL});
2318:
2319: $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
2320: if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
2321: }
2322: } continue {
2323: $curRes = $iterator->next();
2324: }
2325: }
2326:
2327: # Check: Was this only one resource, a map?
2328: if ($resourceCount == 1 && $resource->is_map() && !$self->{FORCE_TOP}) {
2329: my $firstResource = $resource->map_start();
2330: my $finishResource = $resource->map_finish();
2331: return
2332: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
2333: $finishResource, $self->{FILTER},
2334: $self->{ALREADY_SEEN},
2335: $self->{CONDITION}, 0);
2336:
2337: }
2338:
2339: # Set up some bookkeeping information.
2340: $self->{CURRENT_DEPTH} = 0;
2341: $self->{MAX_DEPTH} = $maxDepth;
2342: $self->{STACK} = [];
2343: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2344:
2345: for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
2346: push @{$self->{STACK}}, [];
2347: }
2348:
2349: # Prime the recursion w/ the first resource **5**
2350: push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
2351: $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
2352:
2353: bless ($self);
2354:
2355: return $self;
2356: }
2357:
2358: sub next {
2359: my $self = shift;
2360:
2361: # If we want to return the top-level map object, and haven't yet,
2362: # do so.
2363: if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
2364: $self->{HAVE_RETURNED_0} = 1;
2365: return $self->{NAV_MAP}->getById('0.0');
2366: }
2367:
2368: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
2369: # grab the next from the recursive iterator
2370: my $next = $self->{RECURSIVE_ITERATOR}->next();
2371:
2372: # is it a begin or end map? If so, update the depth
2373: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
2374: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
2375:
2376: # Are we back at depth 0? If so, stop recursing
2377: if ($self->{RECURSIVE_DEPTH} == 0) {
2378: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2379: }
2380:
2381: return $next;
2382: }
2383:
2384: if (defined($self->{FORCE_NEXT})) {
2385: my $tmp = $self->{FORCE_NEXT};
2386: $self->{FORCE_NEXT} = undef;
2387: return $tmp;
2388: }
2389:
2390: # Have we not yet begun? If not, return BEGIN_MAP and
2391: # remember we've started.
2392: if ( !$self->{STARTED} ) {
2393: $self->{STARTED} = 1;
2394: return $self->BEGIN_MAP();
2395: }
2396:
2397: # Here's the guts of the iterator.
2398:
2399: # Find the next resource, if any.
2400: my $found = 0;
2401: my $i = $self->{MAX_DEPTH};
2402: my $newDepth;
2403: my $here;
2404: while ( $i >= 0 && !$found ) {
2405: if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
2406: $here = pop @{$self->{STACK}->[$i]}; # **7**
2407: $found = 1;
2408: $newDepth = $i;
2409: }
2410: $i--;
2411: }
2412:
2413: # If we still didn't find anything, we're done.
2414: if ( !$found ) {
2415: # We need to get back down to the correct branch depth
2416: if ( $self->{CURRENT_DEPTH} > 0 ) {
2417: $self->{CURRENT_DEPTH}--;
2418: return END_BRANCH();
2419: } else {
2420: return END_MAP();
2421: }
2422: }
2423:
2424: # If this is not a resource, it must be an END_BRANCH marker we want
2425: # to return directly.
2426: if (!ref($here)) { # **8**
2427: if ($here == END_BRANCH()) { # paranoia, in case of later extension
2428: $self->{CURRENT_DEPTH}--;
2429: return $here;
2430: }
2431: }
2432:
2433: # Otherwise, it is a resource and it's safe to store in $self->{HERE}
2434: $self->{HERE} = $here;
2435:
2436: # Get to the right level
2437: if ( $self->{CURRENT_DEPTH} > $newDepth ) {
2438: push @{$self->{STACK}->[$newDepth]}, $here;
2439: $self->{CURRENT_DEPTH}--;
2440: return END_BRANCH();
2441: }
2442: if ( $self->{CURRENT_DEPTH} < $newDepth) {
2443: push @{$self->{STACK}->[$newDepth]}, $here;
2444: $self->{CURRENT_DEPTH}++;
2445: return BEGIN_BRANCH();
2446: }
2447:
2448: # If we made it here, we have the next resource, and we're at the
2449: # right branch level. So let's examine the resource for where
2450: # we can get to from here.
2451:
2452: # So we need to look at all the resources we can get to from here,
2453: # categorize them if we haven't seen them, remember if we have a new
2454: my $nextUnfiltered = $here->getNext();
2455: my $maxDepthAdded = -1;
2456:
2457: for (@$nextUnfiltered) {
2458: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
2459: my $depth = $_->{DATA}->{DISPLAY_DEPTH};
2460: push @{$self->{STACK}->[$depth]}, $_;
2461: $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
2462: if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
2463: }
2464: }
2465:
2466: # Is this the end of a branch? If so, all of the resources examined above
2467: # led to lower levels then the one we are currently at, so we push a END_BRANCH
2468: # marker onto the stack so we don't forget.
2469: # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
2470: # BC branch and gets to C, it will see F as the only next resource, but it's
2471: # one level lower. Thus, this is the end of the branch, since there are no
2472: # more resources added to this level or above.
2473: # We don't do this if the examined resource is the finish resource,
2474: # because the condition given above is true, but the "END_MAP" will
2475: # take care of things and we should already be at depth 0.
2476: my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
2477: if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
2478: push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
2479: }
2480:
2481: # That ends the main iterator logic. Now, do we want to recurse
2482: # down this map (if this resource is a map)?
2483: if ($self->{HERE}->is_map() &&
2484: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
2485: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
2486: my $firstResource = $self->{HERE}->map_start();
2487: my $finishResource = $self->{HERE}->map_finish();
2488:
2489: $self->{RECURSIVE_ITERATOR} =
2490: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
2491: $finishResource, $self->{FILTER},
2492: $self->{ALREADY_SEEN}, $self->{CONDITION});
2493: }
2494:
2495: # If this is a blank resource, don't actually return it.
2496: # Should you ever find you need it, make sure to add an option to the code
2497: # that you can use; other things depend on this behavior.
2498: my $browsePriv = $self->{HERE}->browsePriv();
2499: if (!$self->{HERE}->src() ||
2500: (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
2501: return $self->next();
2502: }
2503:
2504: return $self->{HERE};
2505:
2506: }
2507:
2508: =pod
2509:
2510: The other method available on the iterator is B<getStack>, which
2511: returns an array populated with the current 'stack' of maps, as
2512: references to the resource objects. Example: This is useful when
2513: making the navigation map, as we need to check whether we are under a
2514: page map to see if we need to link directly to the resource, or to the
2515: page. The first elements in the array will correspond to the top of
2516: the stack (most inclusive map).
2517:
2518: =cut
2519:
2520: sub getStack {
2521: my $self=shift;
2522:
2523: my @stack;
2524:
2525: $self->populateStack(\@stack);
2526:
2527: return \@stack;
2528: }
2529:
2530: # Private method: Calls the iterators recursively to populate the stack.
2531: sub populateStack {
2532: my $self=shift;
2533: my $stack = shift;
2534:
2535: push @$stack, $self->{HERE} if ($self->{HERE});
2536:
2537: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
2538: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
2539: }
2540: }
2541:
2542: 1;
2543:
2544: package Apache::lonnavmaps::DFSiterator;
2545:
2546: # Not documented in the perldoc: This is a simple iterator that just walks
2547: # through the nav map and presents the resources in a depth-first search
2548: # fashion, ignorant of conditionals, randomized resources, etc. It presents
2549: # BEGIN_MAP and END_MAP, but does not understand branches at all. It is
2550: # useful for pre-processing of some kind, and is in fact used by the main
2551: # iterator that way, but that's about it.
2552: # One could imagine merging this into the init routine of the main iterator,
2553: # but this might as well be left seperate, since it is possible some other
2554: # use might be found for it. - Jeremy
2555:
2556: # Unlike the main iterator, this DOES return all resources, even blank ones.
2557: # The main iterator needs them to correctly preprocess the map.
2558:
2559: sub BEGIN_MAP { return 1; } # begining of a new map
2560: sub END_MAP { return 2; } # end of the map
2561: sub FORWARD { return 1; } # go forward
2562: sub BACKWARD { return 2; }
2563:
2564: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
2565: # filter hash ref (or undef), already seen hash or undef, condition
2566: # (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
2567: sub new {
2568: # magic invocation to create a class instance
2569: my $proto = shift;
2570: my $class = ref($proto) || $proto;
2571: my $self = {};
2572:
2573: $self->{NAV_MAP} = shift;
2574: return undef unless ($self->{NAV_MAP});
2575:
2576: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
2577: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
2578:
2579: # If the given resources are just the ID of the resource, get the
2580: # objects
2581: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
2582: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
2583: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
2584: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
2585:
2586: $self->{FILTER} = shift;
2587:
2588: # A hash, used as a set, of resource already seen
2589: $self->{ALREADY_SEEN} = shift;
2590: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
2591: $self->{CONDITION} = shift;
2592: $self->{DIRECTION} = shift || FORWARD();
2593:
2594: # Flag: Have we started yet?
2595: $self->{STARTED} = 0;
2596:
2597: # Should we continue calling the recursive iterator, if any?
2598: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2599: # The recursive iterator, if any
2600: $self->{RECURSIVE_ITERATOR} = undef;
2601: # Are we recursing on a map, or a branch?
2602: $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
2603: # And the count of how deep it is, so that this iterator can keep track of
2604: # when to pick back up again.
2605: $self->{RECURSIVE_DEPTH} = 0;
2606:
2607: # For keeping track of our branches, we maintain our own stack
2608: $self->{STACK} = [];
2609:
2610: # Start with the first resource
2611: if ($self->{DIRECTION} == FORWARD) {
2612: push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
2613: } else {
2614: push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
2615: }
2616:
2617: bless($self);
2618: return $self;
2619: }
2620:
2621: sub next {
2622: my $self = shift;
2623:
2624: # Are we using a recursive iterator? If so, pull from that and
2625: # watch the depth; we want to resume our level at the correct time.
2626: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
2627: # grab the next from the recursive iterator
2628: my $next = $self->{RECURSIVE_ITERATOR}->next();
2629:
2630: # is it a begin or end map? Update depth if so
2631: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
2632: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
2633:
2634: # Are we back at depth 0? If so, stop recursing.
2635: if ($self->{RECURSIVE_DEPTH} == 0) {
2636: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
2637: }
2638:
2639: return $next;
2640: }
2641:
2642: # Is there a current resource to grab? If not, then return
2643: # END_MAP, which will end the iterator.
2644: if (scalar(@{$self->{STACK}}) == 0) {
2645: return $self->END_MAP();
2646: }
2647:
2648: # Have we not yet begun? If not, return BEGIN_MAP and
2649: # remember that we've started.
2650: if ( !$self->{STARTED} ) {
2651: $self->{STARTED} = 1;
2652: return $self->BEGIN_MAP;
2653: }
2654:
2655: # Get the next resource in the branch
2656: $self->{HERE} = pop @{$self->{STACK}};
2657:
2658: # remember that we've seen this, so we don't return it again later
2659: $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
2660:
2661: # Get the next possible resources
2662: my $nextUnfiltered;
2663: if ($self->{DIRECTION} == FORWARD()) {
2664: $nextUnfiltered = $self->{HERE}->getNext();
2665: } else {
2666: $nextUnfiltered = $self->{HERE}->getPrevious();
2667: }
2668: my $next = [];
2669:
2670: # filter the next possibilities to remove things we've
2671: # already seen.
2672: foreach (@$nextUnfiltered) {
2673: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
2674: push @$next, $_;
2675: }
2676: }
2677:
2678: while (@$next) {
2679: # copy the next possibilities over to the stack
2680: push @{$self->{STACK}}, shift @$next;
2681: }
2682:
2683: # If this is a map and we want to recurse down it... (not filtered out)
2684: if ($self->{HERE}->is_map() &&
2685: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
2686: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
2687: my $firstResource = $self->{HERE}->map_start();
2688: my $finishResource = $self->{HERE}->map_finish();
2689:
2690: $self->{RECURSIVE_ITERATOR} =
2691: Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource,
2692: $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
2693: $self->{CONDITION}, $self->{DIRECTION});
2694: }
2695:
2696: return $self->{HERE};
2697: }
2698:
2699: # Identical to the full iterator methods of the same name. Hate to copy/paste
2700: # but I also hate to "inherit" either iterator from the other.
2701:
2702: sub getStack {
2703: my $self=shift;
2704:
2705: my @stack;
2706:
2707: $self->populateStack(\@stack);
2708:
2709: return \@stack;
2710: }
2711:
2712: # Private method: Calls the iterators recursively to populate the stack.
2713: sub populateStack {
2714: my $self=shift;
2715: my $stack = shift;
2716:
2717: push @$stack, $self->{HERE} if ($self->{HERE});
2718:
2719: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
2720: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
2721: }
2722: }
2723:
2724: 1;
2725:
2726: package Apache::lonnavmaps::resource;
2727:
2728: use Apache::lonnet;
2729:
2730: =pod
2731:
2732: =head1 Object: resource
2733:
2734: A resource object encapsulates a resource in a resource map, allowing
2735: easy manipulation of the resource, querying the properties of the
2736: resource (including user properties), and represents a reference that
2737: can be used as the canonical representation of the resource by
2738: lonnavmap clients like renderers.
2739:
2740: A resource only makes sense in the context of a navmap, as some of the
2741: data is stored in the navmap object.
2742:
2743: You will probably never need to instantiate this object directly. Use
2744: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
2745: starting resource.
2746:
2747: Resource objects respect the parameter_hiddenparts, which suppresses
2748: various parts according to the wishes of the map author. As of this
2749: writing, there is no way to override this parameter, and suppressed
2750: parts will never be returned, nor will their response types or ids be
2751: stored.
2752:
2753: =head2 Public Members
2754:
2755: resource objects have a hash called DATA ($resourceRef->{DATA}) that
2756: you can store whatever you want in. This allows you to easily do
2757: two-pass algorithms without worrying about managing your own
2758: resource->data hash.
2759:
2760: =head2 Methods
2761:
2762: =over 4
2763:
2764: =item * B<new>($navmapRef, $idString):
2765:
2766: The first arg is a reference to the parent navmap object. The second
2767: is the idString of the resource itself. Very rarely, if ever, called
2768: directly. Use the nav map->getByID() method.
2769:
2770: =back
2771:
2772: =cut
2773:
2774: sub new {
2775: # magic invocation to create a class instance
2776: my $proto = shift;
2777: my $class = ref($proto) || $proto;
2778: my $self = {};
2779:
2780: $self->{NAV_MAP} = shift;
2781: $self->{ID} = shift;
2782:
2783: # Store this new resource in the parent nav map's cache.
2784: $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
2785: $self->{RESOURCE_ERROR} = 0;
2786:
2787: # A hash that can be used by two-pass algorithms to store data
2788: # about this resource in. Not used by the resource object
2789: # directly.
2790: $self->{DATA} = {};
2791:
2792: bless($self);
2793:
2794: return $self;
2795: }
2796:
2797: # private function: simplify the NAV_HASH lookups we keep doing
2798: # pass the name, and to automatically append my ID, pass a true val on the
2799: # second param
2800: sub navHash {
2801: my $self = shift;
2802: my $param = shift;
2803: my $id = shift;
2804: return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
2805: }
2806:
2807: =pod
2808:
2809: B<Metadata Retreival>
2810:
2811: These are methods that help you retrieve metadata about the resource:
2812: Method names are based on the fields in the compiled course
2813: representation.
2814:
2815: =over 4
2816:
2817: =item * B<compTitle>:
2818:
2819: Returns a "composite title", that is equal to $res->title() if the
2820: resource has a title, and is otherwise the last part of the URL (e.g.,
2821: "problem.problem").
2822:
2823: =item * B<ext>:
2824:
2825: Returns true if the resource is external.
2826:
2827: =item * B<goesto>:
2828:
2829: Returns the "goesto" value from the compiled nav map. (It is likely
2830: you want to use B<getNext> instead.)
2831:
2832: =item * B<kind>:
2833:
2834: Returns the kind of the resource from the compiled nav map.
2835:
2836: =item * B<randomout>:
2837:
2838: Returns true if this resource was chosen to NOT be shown to the user
2839: by the random map selection feature. In other words, this is usually
2840: false.
2841:
2842: =item * B<randompick>:
2843:
2844: Returns true for a map if the randompick feature is being used on the
2845: map. (?)
2846:
2847: =item * B<src>:
2848:
2849: Returns the source for the resource.
2850:
2851: =item * B<symb>:
2852:
2853: Returns the symb for the resource.
2854:
2855: =item * B<title>:
2856:
2857: Returns the title of the resource.
2858:
2859: =item * B<to>:
2860:
2861: Returns the "to" value from the compiled nav map. (It is likely you
2862: want to use B<getNext> instead.)
2863:
2864: =back
2865:
2866: =cut
2867:
2868: # These info functions can be used directly, as they don't return
2869: # resource information.
2870: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
2871: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
2872: sub from { my $self=shift; return $self->navHash("from_", 1); }
2873: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
2874: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
2875: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
2876: sub randompick {
2877: my $self = shift;
2878: return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
2879: '.0.parameter_randompick'};
2880: }
2881: sub src {
2882: my $self=shift;
2883: return $self->navHash("src_", 1);
2884: }
2885: sub symb {
2886: my $self=shift;
2887: (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
2888: my $symbSrc = &Apache::lonnet::declutter($self->src());
2889: return &Apache::lonnet::declutter(
2890: $self->navHash('map_id_'.$first))
2891: . '___' . $second . '___' . $symbSrc;
2892: }
2893: sub title { my $self=shift; return $self->navHash("title_", 1); }
2894: sub to { my $self=shift; return $self->navHash("to_", 1); }
2895: sub compTitle {
2896: my $self = shift;
2897: my $title = $self->title();
2898: $title=~s/\&colon\;/\:/gs;
2899: if (!$title) {
2900: $title = $self->src();
2901: $title = substr($title, rindex($title, '/') + 1);
2902: }
2903: return $title;
2904: }
2905: =pod
2906:
2907: B<Predicate Testing the Resource>
2908:
2909: These methods are shortcuts to deciding if a given resource has a given property.
2910:
2911: =over 4
2912:
2913: =item * B<is_map>:
2914:
2915: Returns true if the resource is a map type.
2916:
2917: =item * B<is_problem>:
2918:
2919: Returns true if the resource is a problem type, false
2920: otherwise. (Looks at the extension on the src field; might need more
2921: to work correctly.)
2922:
2923: =item * B<is_page>:
2924:
2925: Returns true if the resource is a page.
2926:
2927: =item * B<is_sequence>:
2928:
2929: Returns true if the resource is a sequence.
2930:
2931: =back
2932:
2933: =cut
2934:
2935:
2936: sub is_html {
2937: my $self=shift;
2938: my $src = $self->src();
2939: return ($src =~ /html$/);
2940: }
2941: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
2942: sub is_page {
2943: my $self=shift;
2944: my $src = $self->src();
2945: return ($src =~ /page$/);
2946: }
2947: sub is_problem {
2948: my $self=shift;
2949: my $src = $self->src();
2950: return ($src =~ /problem$/);
2951: }
2952: sub is_sequence {
2953: my $self=shift;
2954: my $src = $self->src();
2955: return ($src =~ /sequence$/);
2956: }
2957:
2958: # Private method: Shells out to the parmval in the nav map, handler parts.
2959: sub parmval {
2960: my $self = shift;
2961: my $what = shift;
2962: my $part = shift;
2963: if (!defined($part)) {
2964: $part = '0';
2965: }
2966: return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
2967: }
2968:
2969: =pod
2970:
2971: B<Map Methods>
2972:
2973: These methods are useful for getting information about the map
2974: properties of the resource, if the resource is a map (B<is_map>).
2975:
2976: =over 4
2977:
2978: =item * B<map_finish>:
2979:
2980: Returns a reference to a resource object corresponding to the finish
2981: resource of the map.
2982:
2983: =item * B<map_pc>:
2984:
2985: Returns the pc value of the map, which is the first number that
2986: appears in the resource ID of the resources in the map, and is the
2987: number that appears around the middle of the symbs of the resources in
2988: that map.
2989:
2990: =item * B<map_start>:
2991:
2992: Returns a reference to a resource object corresponding to the start
2993: resource of the map.
2994:
2995: =item * B<map_type>:
2996:
2997: Returns a string with the type of the map in it.
2998:
2999: =back
3000:
3001: =cut
3002:
3003: sub map_finish {
3004: my $self = shift;
3005: my $src = $self->src();
3006: $src = Apache::lonnet::clutter($src);
3007: my $res = $self->navHash("map_finish_$src", 0);
3008: $res = $self->{NAV_MAP}->getById($res);
3009: return $res;
3010: }
3011: sub map_pc {
3012: my $self = shift;
3013: my $src = $self->src();
3014: return $self->navHash("map_pc_$src", 0);
3015: }
3016: sub map_start {
3017: my $self = shift;
3018: my $src = $self->src();
3019: $src = Apache::lonnet::clutter($src);
3020: my $res = $self->navHash("map_start_$src", 0);
3021: $res = $self->{NAV_MAP}->getById($res);
3022: return $res;
3023: }
3024: sub map_type {
3025: my $self = shift;
3026: my $pc = $self->map_pc();
3027: return $self->navHash("map_type_$pc", 0);
3028: }
3029:
3030:
3031:
3032: #####
3033: # Property queries
3034: #####
3035:
3036: # These functions will be responsible for returning the CORRECT
3037: # VALUE for the parameter, no matter what. So while they may look
3038: # like direct calls to parmval, they can be more then that.
3039: # So, for instance, the duedate function should use the "duedatetype"
3040: # information, rather then the resource object user.
3041:
3042: =pod
3043:
3044: =head2 Resource Parameters
3045:
3046: In order to use the resource parameters correctly, the nav map must
3047: have been instantiated with genCourseAndUserOptions set to true, so
3048: the courseopt and useropt is read correctly. Then, you can call these
3049: functions to get the relevant parameters for the resource. Each
3050: function defaults to part "0", but can be directed to another part by
3051: passing the part as the parameter.
3052:
3053: These methods are responsible for getting the parameter correct, not
3054: merely reflecting the contents of the GDBM hashes. As we move towards
3055: dates relative to other dates, these methods should be updated to
3056: reflect that. (Then, anybody using these methods will not have to update
3057: their code.)
3058:
3059: =over 4
3060:
3061: =item * B<acc>:
3062:
3063: Get the Client IP/Name Access Control information.
3064:
3065: =item * B<answerdate>:
3066:
3067: Get the answer-reveal date for the problem.
3068:
3069: =item * B<duedate>:
3070:
3071: Get the due date for the problem.
3072:
3073: =item * B<tries>:
3074:
3075: Get the number of tries the student has used on the problem.
3076:
3077: =item * B<maxtries>:
3078:
3079: Get the number of max tries allowed.
3080:
3081: =item * B<opendate>:
3082:
3083: Get the open date for the problem.
3084:
3085: =item * B<sig>:
3086:
3087: Get the significant figures setting.
3088:
3089: =item * B<tol>:
3090:
3091: Get the tolerance for the problem.
3092:
3093: =item * B<tries>:
3094:
3095: Get the number of tries the user has already used on the problem.
3096:
3097: =item * B<type>:
3098:
3099: Get the question type for the problem.
3100:
3101: =item * B<weight>:
3102:
3103: Get the weight for the problem.
3104:
3105: =back
3106:
3107: =cut
3108:
3109: sub acc {
3110: (my $self, my $part) = @_;
3111: return $self->parmval("acc", $part);
3112: }
3113: sub answerdate {
3114: (my $self, my $part) = @_;
3115: # Handle intervals
3116: if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
3117: return $self->duedate($part) +
3118: $self->parmval("answerdate", $part);
3119: }
3120: return $self->parmval("answerdate", $part);
3121: }
3122: sub awarded { my $self = shift; return $self->queryRestoreHash('awarded', shift); }
3123: sub duedate {
3124: (my $self, my $part) = @_;
3125: return $self->parmval("duedate", $part);
3126: }
3127: sub maxtries {
3128: (my $self, my $part) = @_;
3129: return $self->parmval("maxtries", $part);
3130: }
3131: sub opendate {
3132: (my $self, my $part) = @_;
3133: if ($self->parmval("opendate.type", $part) eq 'date_interval') {
3134: return $self->duedate($part) -
3135: $self->parmval("opendate", $part);
3136: }
3137: return $self->parmval("opendate");
3138: }
3139: sub problemstatus {
3140: (my $self, my $part) = @_;
3141: return $self->parmval("problemstatus", $part);
3142: }
3143: sub sig {
3144: (my $self, my $part) = @_;
3145: return $self->parmval("sig", $part);
3146: }
3147: sub tol {
3148: (my $self, my $part) = @_;
3149: return $self->parmval("tol", $part);
3150: }
3151: sub tries {
3152: my $self = shift;
3153: my $tries = $self->queryRestoreHash('tries', shift);
3154: if (!defined($tries)) { return '0';}
3155: return $tries;
3156: }
3157: sub type {
3158: (my $self, my $part) = @_;
3159: return $self->parmval("type", $part);
3160: }
3161: sub weight {
3162: my $self = shift; my $part = shift;
3163: return $self->parmval("weight", $part);
3164: }
3165:
3166: # Multiple things need this
3167: sub getReturnHash {
3168: my $self = shift;
3169:
3170: if (!defined($self->{RETURN_HASH})) {
3171: my %tmpHash = &Apache::lonnet::restore($self->symb());
3172: $self->{RETURN_HASH} = \%tmpHash;
3173: }
3174: }
3175:
3176: ######
3177: # Status queries
3178: ######
3179:
3180: # These methods query the status of problems.
3181:
3182: # If we need to count parts, this function determines the number of
3183: # parts from the metadata. When called, it returns a reference to a list
3184: # of strings corresponding to the parts. (Thus, using it in a scalar context
3185: # tells you how many parts you have in the problem:
3186: # $partcount = scalar($resource->countParts());
3187: # Don't use $self->{PARTS} directly because you don't know if it's been
3188: # computed yet.
3189:
3190: =pod
3191:
3192: =head2 Resource misc
3193:
3194: Misc. functions for the resource.
3195:
3196: =over 4
3197:
3198: =item * B<hasDiscussion>:
3199:
3200: Returns a false value if there has been discussion since the user last
3201: logged in, true if there has. Always returns false if the discussion
3202: data was not extracted when the nav map was constructed.
3203:
3204: =item * B<getFeedback>:
3205:
3206: Gets the feedback for the resource and returns the raw feedback string
3207: for the resource, or the null string if there is no feedback or the
3208: email data was not extracted when the nav map was constructed. Usually
3209: used like this:
3210:
3211: for (split(/\,/, $res->getFeedback())) {
3212: my $link = &Apache::lonnet::escape($_);
3213: ...
3214:
3215: and use the link as appropriate.
3216:
3217: =cut
3218:
3219: sub hasDiscussion {
3220: my $self = shift;
3221: return $self->{NAV_MAP}->hasDiscussion($self->symb());
3222: }
3223:
3224: sub getFeedback {
3225: my $self = shift;
3226: my $source = $self->src();
3227: if ($source =~ /^\/res\//) { $source = substr $source, 5; }
3228: return $self->{NAV_MAP}->getFeedback($source);
3229: }
3230:
3231: sub getErrors {
3232: my $self = shift;
3233: my $source = $self->src();
3234: if ($source =~ /^\/res\//) { $source = substr $source, 5; }
3235: return $self->{NAV_MAP}->getErrors($source);
3236: }
3237:
3238: =pod
3239:
3240: =item * B<parts>():
3241:
3242: Returns a list reference containing sorted strings corresponding to
3243: each part of the problem. Single part problems have only a part '0'.
3244: Multipart problems do not return their part '0', since they typically
3245: do not really matter.
3246:
3247: =item * B<countParts>():
3248:
3249: Returns the number of parts of the problem a student can answer. Thus,
3250: for single part problems, returns 1. For multipart, it returns the
3251: number of parts in the problem, not including psuedo-part 0.
3252:
3253: =item * B<multipart>():
3254:
3255: Returns true if the problem is multipart, false otherwise. Use this instead
3256: of countParts if all you want is multipart/not multipart.
3257:
3258: =item * B<responseType>($part):
3259:
3260: Returns the response type of the part, without the word "response" on the
3261: end. Example return values: 'string', 'essay', 'numeric', etc.
3262:
3263: =item * B<responseIds>($part):
3264:
3265: Retreives the response IDs for the given part as an array reference containing
3266: strings naming the response IDs. This may be empty.
3267:
3268: =back
3269:
3270: =cut
3271:
3272: sub parts {
3273: my $self = shift;
3274:
3275: if ($self->ext) { return []; }
3276:
3277: $self->extractParts();
3278: return $self->{PARTS};
3279: }
3280:
3281: sub countParts {
3282: my $self = shift;
3283:
3284: my $parts = $self->parts();
3285:
3286: # If I left this here, then it's not necessary.
3287: #my $delta = 0;
3288: #for my $part (@$parts) {
3289: # if ($part eq '0') { $delta--; }
3290: #}
3291:
3292: if ($self->{RESOURCE_ERROR}) {
3293: return 0;
3294: }
3295:
3296: return scalar(@{$parts}); # + $delta;
3297: }
3298:
3299: sub multipart {
3300: my $self = shift;
3301: return $self->countParts() > 1;
3302: }
3303:
3304: sub responseType {
3305: my $self = shift;
3306: my $part = shift;
3307:
3308: $self->extractParts();
3309: return $self->{RESPONSE_TYPE}->{$part};
3310: }
3311:
3312: sub responseIds {
3313: my $self = shift;
3314: my $part = shift;
3315:
3316: $self->extractParts();
3317: return $self->{RESPONSE_IDS}->{$part};
3318: }
3319:
3320: # Private function: Extracts the parts information, both part names and
3321: # part types, and saves it.
3322: sub extractParts {
3323: my $self = shift;
3324:
3325: return if (defined($self->{PARTS}));
3326: return if ($self->ext);
3327:
3328: $self->{PARTS} = [];
3329:
3330: my %parts;
3331:
3332: # Retrieve part count, if this is a problem
3333: if ($self->is_problem()) {
3334: my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
3335: if (!$metadata) {
3336: $self->{RESOURCE_ERROR} = 1;
3337: $self->{PARTS} = [];
3338: $self->{PART_TYPE} = {};
3339: return;
3340: }
3341: foreach (split(/\,/,$metadata)) {
3342: if ($_ =~ /^part_(.*)$/) {
3343: my $part = $1;
3344: # This floods the logs if it blows up
3345: if (defined($parts{$part})) {
3346: Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->symb());
3347: }
3348:
3349: # check to see if part is turned off.
3350:
3351: if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
3352: $parts{$part} = 1;
3353: }
3354: }
3355: }
3356:
3357:
3358: my @sortedParts = sort keys %parts;
3359: $self->{PARTS} = \@sortedParts;
3360:
3361: my %responseIdHash;
3362: my %responseTypeHash;
3363:
3364:
3365: # Init the responseIdHash
3366: foreach (@{$self->{PARTS}}) {
3367: $responseIdHash{$_} = [];
3368: }
3369:
3370: # Now, the unfortunate thing about this is that parts, part name, and
3371: # response if are delimited by underscores, but both the part
3372: # name and response id can themselves have underscores in them.
3373: # So we have to use our knowlege of part names to figure out
3374: # where the part names begin and end, and even then, it is possible
3375: # to construct ambiguous situations.
3376: foreach (split /,/, $metadata) {
3377: if ($_ =~ /^([a-zA-Z]+)response_(.*)/) {
3378: my $responseType = $1;
3379: my $partStuff = $2;
3380: my $partIdSoFar = '';
3381: my @partChunks = split /_/, $partStuff;
3382: my $i = 0;
3383:
3384: for ($i = 0; $i < scalar(@partChunks); $i++) {
3385: if ($partIdSoFar) { $partIdSoFar .= '_'; }
3386: $partIdSoFar .= $partChunks[$i];
3387: if ($parts{$partIdSoFar}) {
3388: my @otherChunks = @partChunks[$i+1..$#partChunks];
3389: my $responseId = join('_', @otherChunks);
3390: push @{$responseIdHash{$partIdSoFar}}, $responseId;
3391: $responseTypeHash{$partIdSoFar} = $responseType;
3392: last;
3393: }
3394: }
3395: }
3396: }
3397:
3398: $self->{RESPONSE_IDS} = \%responseIdHash;
3399: $self->{RESPONSE_TYPES} = \%responseTypeHash;
3400: }
3401:
3402: return;
3403: }
3404:
3405: =pod
3406:
3407: =head2 Resource Status
3408:
3409: Problem resources have status information, reflecting their various
3410: dates and completion statuses.
3411:
3412: There are two aspects to the status: the date-related information and
3413: the completion information.
3414:
3415: Idiomatic usage of these two methods would probably look something
3416: like
3417:
3418: foreach ($resource->parts()) {
3419: my $dateStatus = $resource->getDateStatus($_);
3420: my $completionStatus = $resource->getCompletionStatus($_);
3421:
3422: or
3423:
3424: my $status = $resource->status($_);
3425:
3426: ... use it here ...
3427: }
3428:
3429: Which you use depends on exactly what you are looking for. The
3430: status() function has been optimized for the nav maps display and may
3431: not precisely match what you need elsewhere.
3432:
3433: The symbolic constants shown below can be accessed through the
3434: resource object: C<$res->OPEN>.
3435:
3436: =over 4
3437:
3438: =item * B<getDateStatus>($part):
3439:
3440: ($part defaults to 0). A convenience function that returns a symbolic
3441: constant telling you about the date status of the part. The possible
3442: return values are:
3443:
3444: =back
3445:
3446: B<Date Codes>
3447:
3448: =over 4
3449:
3450: =item * B<OPEN_LATER>:
3451:
3452: The problem will be opened later.
3453:
3454: =item * B<OPEN>:
3455:
3456: Open and not yet due.
3457:
3458:
3459: =item * B<PAST_DUE_ANSWER_LATER>:
3460:
3461: The due date has passed, but the answer date has not yet arrived.
3462:
3463: =item * B<PAST_DUE_NO_ANSWER>:
3464:
3465: The due date has passed and there is no answer opening date set.
3466:
3467: =item * B<ANSWER_OPEN>:
3468:
3469: The answer date is here.
3470:
3471: =item * B<NETWORK_FAILURE>:
3472:
3473: The information is unknown due to network failure.
3474:
3475: =back
3476:
3477: =cut
3478:
3479: # Apparently the compiler optimizes these into constants automatically
3480: sub OPEN_LATER { return 0; }
3481: sub OPEN { return 1; }
3482: sub PAST_DUE_NO_ANSWER { return 2; }
3483: sub PAST_DUE_ANSWER_LATER { return 3; }
3484: sub ANSWER_OPEN { return 4; }
3485: sub NOTHING_SET { return 5; }
3486: sub NETWORK_FAILURE { return 100; }
3487:
3488: # getDateStatus gets the date status for a given problem part.
3489: # Because answer date, due date, and open date are fully independent
3490: # (i.e., it is perfectly possible to *only* have an answer date),
3491: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
3492: # (past, future, none given). This function handles this with a decision
3493: # tree. Read the comments to follow the decision tree.
3494:
3495: sub getDateStatus {
3496: my $self = shift;
3497: my $part = shift;
3498: $part = "0" if (!defined($part));
3499:
3500: # Always return network failure if there was one.
3501: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
3502:
3503: my $now = time();
3504:
3505: my $open = $self->opendate($part);
3506: my $due = $self->duedate($part);
3507: my $answer = $self->answerdate($part);
3508:
3509: if (!$open && !$due && !$answer) {
3510: # no data on the problem at all
3511: # should this be the same as "open later"? think multipart.
3512: return $self->NOTHING_SET;
3513: }
3514: if (!$open || $now < $open) {return $self->OPEN_LATER}
3515: if (!$due || $now < $due) {return $self->OPEN}
3516: if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
3517: if ($answer) { return $self->ANSWER_OPEN; }
3518: return PAST_DUE_NO_ANSWER;
3519: }
3520:
3521: =pod
3522:
3523: B<>
3524:
3525: =over 4
3526:
3527: =item * B<getCompletionStatus>($part):
3528:
3529: ($part defaults to 0.) A convenience function that returns a symbolic
3530: constant telling you about the completion status of the part, with the
3531: following possible results:
3532:
3533: =back
3534:
3535: B<Completion Codes>
3536:
3537: =over 4
3538:
3539: =item * B<NOT_ATTEMPTED>:
3540:
3541: Has not been attempted at all.
3542:
3543: =item * B<INCORRECT>:
3544:
3545: Attempted, but wrong by student.
3546:
3547: =item * B<INCORRECT_BY_OVERRIDE>:
3548:
3549: Attempted, but wrong by instructor override.
3550:
3551: =item * B<CORRECT>:
3552:
3553: Correct or correct by instructor.
3554:
3555: =item * B<CORRECT_BY_OVERRIDE>:
3556:
3557: Correct by instructor override.
3558:
3559: =item * B<EXCUSED>:
3560:
3561: Excused. Not yet implemented.
3562:
3563: =item * B<NETWORK_FAILURE>:
3564:
3565: Information not available due to network failure.
3566:
3567: =item * B<ATTEMPTED>:
3568:
3569: Attempted, and not yet graded.
3570:
3571: =back
3572:
3573: =cut
3574:
3575: sub NOT_ATTEMPTED { return 10; }
3576: sub INCORRECT { return 11; }
3577: sub INCORRECT_BY_OVERRIDE { return 12; }
3578: sub CORRECT { return 13; }
3579: sub CORRECT_BY_OVERRIDE { return 14; }
3580: sub EXCUSED { return 15; }
3581: sub ATTEMPTED { return 16; }
3582:
3583: sub getCompletionStatus {
3584: my $self = shift;
3585: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
3586:
3587: my $status = $self->queryRestoreHash('solved', shift);
3588:
3589: # Left as seperate if statements in case we ever do more with this
3590: if ($status eq 'correct_by_student') {return $self->CORRECT;}
3591: if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
3592: if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
3593: if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
3594: if ($status eq 'excused') {return $self->EXCUSED; }
3595: if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
3596: return $self->NOT_ATTEMPTED;
3597: }
3598:
3599: sub queryRestoreHash {
3600: my $self = shift;
3601: my $hashentry = shift;
3602: my $part = shift;
3603: $part = "0" if (!defined($part) || $part eq '');
3604: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
3605:
3606: $self->getReturnHash();
3607:
3608: return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
3609: }
3610:
3611: =pod
3612:
3613: B<Composite Status>
3614:
3615: Along with directly returning the date or completion status, the
3616: resource object includes a convenience function B<status>() that will
3617: combine the two status tidbits into one composite status that can
3618: represent the status of the resource as a whole. This method represents
3619: the concept of the thing we want to display to the user on the nav maps
3620: screen, which is a combination of completion and open status. The precise logic is
3621: documented in the comments of the status method. The following results
3622: may be returned, all available as methods on the resource object
3623: ($res->NETWORK_FAILURE): In addition to the return values that match
3624: the date or completion status, this function can return "ANSWER_SUBMITTED"
3625: if that problemstatus parameter value is set to No, suppressing the
3626: incorrect/correct feedback.
3627:
3628: =over 4
3629:
3630: =item * B<NETWORK_FAILURE>:
3631:
3632: The network has failed and the information is not available.
3633:
3634: =item * B<NOTHING_SET>:
3635:
3636: No dates have been set for this problem (part) at all. (Because only
3637: certain parts of a multi-part problem may be assigned, this can not be
3638: collapsed into "open later", as we do not know a given part will EVER
3639: be opened. For single part, this is the same as "OPEN_LATER".)
3640:
3641: =item * B<CORRECT>:
3642:
3643: For any reason at all, the part is considered correct.
3644:
3645: =item * B<EXCUSED>:
3646:
3647: For any reason at all, the problem is excused.
3648:
3649: =item * B<PAST_DUE_NO_ANSWER>:
3650:
3651: The problem is past due, not considered correct, and no answer date is
3652: set.
3653:
3654: =item * B<PAST_DUE_ANSWER_LATER>:
3655:
3656: The problem is past due, not considered correct, and an answer date in
3657: the future is set.
3658:
3659: =item * B<ANSWER_OPEN>:
3660:
3661: The problem is past due, not correct, and the answer is now available.
3662:
3663: =item * B<OPEN_LATER>:
3664:
3665: The problem is not yet open.
3666:
3667: =item * B<TRIES_LEFT>:
3668:
3669: The problem is open, has been tried, is not correct, but there are
3670: tries left.
3671:
3672: =item * B<INCORRECT>:
3673:
3674: The problem is open, and all tries have been used without getting the
3675: correct answer.
3676:
3677: =item * B<OPEN>:
3678:
3679: The item is open and not yet tried.
3680:
3681: =item * B<ATTEMPTED>:
3682:
3683: The problem has been attempted.
3684:
3685: =item * B<ANSWER_SUBMITTED>:
3686:
3687: An answer has been submitted, but the student should not see it.
3688:
3689: =back
3690:
3691: =cut
3692:
3693: sub TRIES_LEFT { return 20; }
3694: sub ANSWER_SUBMITTED { return 21; }
3695:
3696: sub status {
3697: my $self = shift;
3698: my $part = shift;
3699: if (!defined($part)) { $part = "0"; }
3700: my $completionStatus = $self->getCompletionStatus($part);
3701: my $dateStatus = $self->getDateStatus($part);
3702:
3703: # What we have is a two-dimensional matrix with 4 entries on one
3704: # dimension and 5 entries on the other, which we want to colorize,
3705: # plus network failure and "no date data at all".
3706:
3707: if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
3708:
3709: my $suppressFeedback = lc($self->parmval("problemstatus", $part)) eq 'no';
3710:
3711: # There are a few whole rows we can dispose of:
3712: if ($completionStatus == CORRECT ||
3713: $completionStatus == CORRECT_BY_OVERRIDE ) {
3714: return $suppressFeedback? ANSWER_SUBMITTED : CORRECT;
3715: }
3716:
3717: if ($completionStatus == ATTEMPTED) {
3718: return ATTEMPTED;
3719: }
3720:
3721: # If it's EXCUSED, then return that no matter what
3722: if ($completionStatus == EXCUSED) {
3723: return EXCUSED;
3724: }
3725:
3726: if ($dateStatus == NOTHING_SET) {
3727: return NOTHING_SET;
3728: }
3729:
3730: # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
3731: # by 4 matrix (date statuses).
3732:
3733: if ($dateStatus == PAST_DUE_ANSWER_LATER ||
3734: $dateStatus == PAST_DUE_NO_ANSWER ) {
3735: return $dateStatus;
3736: }
3737:
3738: if ($dateStatus == ANSWER_OPEN) {
3739: return ANSWER_OPEN;
3740: }
3741:
3742: # Now: (incorrect, incorrect_override, not_attempted) x
3743: # (open_later), (open)
3744:
3745: if ($dateStatus == OPEN_LATER) {
3746: return OPEN_LATER;
3747: }
3748:
3749: # If it's WRONG...
3750: if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
3751: # and there are TRIES LEFT:
3752: if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
3753: return TRIES_LEFT;
3754: }
3755: return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
3756: }
3757:
3758: # Otherwise, it's untried and open
3759: return OPEN;
3760: }
3761:
3762: =pod
3763:
3764: B<Completable>
3765:
3766: The completable method represents the concept of I<whether the student can
3767: currently do the problem>. If the student can do the problem, which means
3768: that it is open, there are tries left, and if the problem is manually graded
3769: or the grade is suppressed via problemstatus, the student has not tried it
3770: yet, then the method returns 1. Otherwise, it returns 0, to indicate that
3771: either the student has tried it and there is no feedback, or that for
3772: some reason it is no longer completable (not open yet, successfully completed,
3773: out of tries, etc.). As an example, this is used as the filter for the
3774: "Uncompleted Homework" option for the nav maps.
3775:
3776: If this does not quite meet your needs, do not fiddle with it (unless you are
3777: fixing it to better match the student's conception of "completable" because
3778: it's broken somehow)... make a new method.
3779:
3780: =cut
3781:
3782: sub completable {
3783: my $self = shift;
3784: if (!$self->is_problem()) { return 0; }
3785: my $partCount = $self->countParts();
3786:
3787: foreach my $part (@{$self->parts()}) {
3788: if ($part eq '0' && $partCount != 1) { next; }
3789: my $status = $self->status($part);
3790: # "If any of the parts are open, or have tries left (implies open),
3791: # and it is not "attempted" (manually graded problem), it is
3792: # not "complete"
3793: if (!(($status == OPEN() || $status == TRIES_LEFT())
3794: && $self->getCompletionStatus($part) != ATTEMPTED()
3795: && $status != ANSWER_SUBMITTED())) {
3796: return 0;
3797: }
3798: }
3799:
3800: # If all the parts were complete, so was this problem.
3801: return 1;
3802: }
3803:
3804: =pod
3805:
3806: =head2 Resource/Nav Map Navigation
3807:
3808: =over 4
3809:
3810: =item * B<getNext>():
3811:
3812: Retreive an array of the possible next resources after this
3813: one. Always returns an array, even in the one- or zero-element case.
3814:
3815: =item * B<getPrevious>():
3816:
3817: Retreive an array of the possible previous resources from this
3818: one. Always returns an array, even in the one- or zero-element case.
3819:
3820: =cut
3821:
3822: sub getNext {
3823: my $self = shift;
3824: my @branches;
3825: my $to = $self->to();
3826: foreach my $branch ( split(/,/, $to) ) {
3827: my $choice = $self->{NAV_MAP}->getById($branch);
3828: my $next = $choice->goesto();
3829: $next = $self->{NAV_MAP}->getById($next);
3830:
3831: push @branches, $next;
3832: }
3833: return \@branches;
3834: }
3835:
3836: sub getPrevious {
3837: my $self = shift;
3838: my @branches;
3839: my $from = $self->from();
3840: foreach my $branch ( split /,/, $from) {
3841: my $choice = $self->{NAV_MAP}->getById($branch);
3842: my $prev = $choice->comesfrom();
3843: $prev = $self->{NAV_MAP}->getById($prev);
3844:
3845: push @branches, $prev;
3846: }
3847: return \@branches;
3848: }
3849:
3850: sub browsePriv {
3851: my $self = shift;
3852: if (defined($self->{BROWSE_PRIV})) {
3853: return $self->{BROWSE_PRIV};
3854: }
3855:
3856: $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
3857: }
3858:
3859: =pod
3860:
3861: =back
3862:
3863: =cut
3864:
3865: 1;
3866:
3867: __END__
3868:
3869:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>