1:
2: # The LearningOnline Network with CAPA
3: # Navigate Maps Handler
4: #
5: # $Id: lonnavmaps.pm,v 1.99 2002/11/08 18:44:02 bowersj2 Exp $
6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27: # http://www.lon-capa.org/
28: #
29: # (Page Handler
30: #
31: # (TeX Content Handler
32: #
33: # 05/29/00,05/30 Gerd Kortemeyer)
34: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
35: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
36: #
37: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
38: # YEAR=2002
39: # 1/1 Gerd Kortemeyer
40: #
41:
42: package Apache::lonnavmaps;
43:
44: use strict;
45: use Apache::Constants qw(:common :http);
46: use Apache::lonnet();
47: use Apache::loncommon();
48: use GDBM_File;
49: use POSIX qw (floor strftime);
50:
51: sub handler {
52: my $r = shift;
53:
54: &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
55:
56: # Handle header-only request
57: if ($r->header_only) {
58: if ($ENV{'browser.mathml'}) {
59: $r->content_type('text/xml');
60: } else {
61: $r->content_type('text/html');
62: }
63: $r->send_http_header;
64: return OK;
65: }
66:
67: # Send header, don't cache this page
68: if ($ENV{'browser.mathml'}) {
69: $r->content_type('text/xml');
70: } else {
71: $r->content_type('text/html');
72: }
73: &Apache::loncommon::no_cache($r);
74: $r->send_http_header;
75:
76: # Create the nav map the nav map
77: my $navmap = Apache::lonnavmaps::navmap->new(
78: $ENV{"request.course.fn"}.".db",
79: $ENV{"request.course.fn"}."_parms.db", 1, 1);
80:
81:
82: if (!defined($navmap)) {
83: my $requrl = $r->uri;
84: $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
85: return HTTP_NOT_ACCEPTABLE;
86: }
87:
88: # Header
89: $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
90: ''));
91: $r->print('<script>window.focus();</script>');
92: my $desc=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};
93: $r->print('<table border="0" cellpadding="2" cellspacing="0">');
94: my $date=localtime;
95: $r->print('<tr><td align="right" valign="bottom">Key: </td>');
96: if ($navmap->{LAST_CHECK}) {
97: $r->print('<td align="center" valign="bottom"> '.
98: '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
99: strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
100: '</td><td align="center" valign="bottom"> '.
101: '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
102: '</td>');
103: } else {
104: $r->print('<td align="center" valign="bottom"> '.
105: '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
106: ' <img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
107: '</td>');
108: }
109: $r->print('</tr></table>');
110: my $condition = 0;
111: if ($ENV{'form.condition'}) {
112: $condition = 1;
113: }
114:
115: if ($condition) {
116: $r->print('<a href="navmaps?condition=0&filter=">Close All Folders</a>');
117: } else {
118: $r->print('<a href="navmaps?condition=1&filter=">Open All Folders</a>');
119: }
120:
121: $r->print('<br> ');
122: $r->rflush();
123:
124: # Now that we've displayed some stuff to the user, init the navmap
125: $navmap->init();
126:
127: # Check that it's defined
128: if (!($navmap->courseMapDefined())) {
129: $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
130: '</body></html>');
131: return OK;
132: }
133:
134: # Grab a resource object so we have access to the constants; this
135: # is technically not proper, but should be harmless
136: my $res = $navmap->firstResource();
137:
138: # Defines a status->color mapping, null string means don't color
139: my %colormap =
140: ( $res->NETWORK_FAILURE => '',
141: $res->CORRECT => '',
142: $res->EXCUSED => '#BBBBFF',
143: $res->PAST_DUE_ANSWER_LATER => '',
144: $res->PAST_DUE_NO_ANSWER => '',
145: $res->ANSWER_OPEN => '#CCFFCC',
146: $res->OPEN_LATER => '',
147: $res->TRIES_LEFT => '',
148: $res->INCORRECT => '',
149: $res->OPEN => '',
150: $res->NOTHING_SET => '' );
151: # And a special case in the nav map; what to do when the assignment
152: # is not yet done and due in less then 24 hours
153: my $hurryUpColor = "#FF0000";
154:
155: my %statusIconMap =
156: ( $res->NETWORK_FAILURE => '',
157: $res->NOTHING_SET => '',
158: $res->CORRECT => 'navmap.correct.gif',
159: $res->EXCUSED => 'navmap.correct.gif',
160: $res->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
161: $res->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
162: $res->ANSWER_OPEN => 'navmap.wrong.gif',
163: $res->OPEN_LATER => '',
164: $res->TRIES_LEFT => 'navmap.open.gif',
165: $res->INCORRECT => 'navmap.wrong.gif',
166: $res->OPEN => 'navmap.open.gif',
167: $res->ATTEMPTED => 'navmap.open.gif' );
168:
169: my %iconAltTags =
170: ( 'navmap.correct.gif' => 'Correct',
171: 'navmap.wrong.gif' => 'Incorrect',
172: 'navmap.open.gif' => 'Open' );
173:
174: my %condenseStatuses =
175: ( $res->NETWORK_FAILURE => 1,
176: $res->NOTHING_SET => 1,
177: $res->CORRECT => 1 );
178:
179: my %filterHash;
180: # Figure out what we're not displaying
181: foreach (split(/\,/, $ENV{"form.filter"})) {
182: if ($_) {
183: $filterHash{$_} = "1";
184: }
185: }
186:
187: # Is this a new-style course? If so, we want to suppress showing the top-level
188: # maps in their own folders, in favor of "inlining" them.
189: my $topResource = $navmap->getById("0.0");
190: my $inlineTopLevelMaps = $topResource->src() =~ m|^/uploaded/.*default\.sequence$|;
191:
192: my $currenturl = $ENV{'form.postdata'};
193: $currenturl=~s/^http\:\/\///;
194: $currenturl=~s/^[^\/]+//;
195: # alreadyHere allows us to only open the maps necessary to view
196: # the current location once, while at the same time remembering
197: # the current location. Without that check, the user would never
198: # be able to close those maps; the user would close it, and the
199: # currenturl scan would re-open it.
200: my $queryAdd = "postdata=" . &Apache::lonnet::escape($currenturl) .
201: "&alreadyHere=1";
202:
203: # Begin the HTML table
204: # four cols: resource + indent, chat+feedback, icon, text string
205: $r->print('<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n");
206:
207: # This needs to be updated to use symbs from the remote,
208: # instead of uris. The changes to this and the main rendering
209: # loop should be obvious.
210: # Here's a simple example of the iterator.
211: # Preprocess the map: Look for current URL, force inlined maps to display
212:
213: # This currently does very little...
214: #my $mapEventualIterator = Apache::lonnavmaps::iterator->new($navmap, undef, undef, {},
215: #undef, $condition);
216:
217: my $mapIterator = $navmap->getIterator(undef, undef, {}, 1);
218: my $found = 0;
219: my $depth = 1;
220: my $currentUrlIndex = 0; # keeps track of when the current resource is found,
221: # so we can back up a few and put the anchor above the
222: # current resource
223: $mapIterator->next(); # discard the first BEGIN_MAP
224: my $curRes = $mapIterator->next();
225: my $counter = 0;
226:
227: while ($depth > 0) {
228: if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
229: if ($curRes == $mapIterator->END_MAP()) { $depth--; }
230:
231: if (ref($curRes)) { $counter++; }
232:
233: my $mapStack = $mapIterator->getStack();
234: if ($currenturl && !$ENV{'form.alreadyHere'} && ref($curRes) &&
235: $curRes->src() eq $currenturl) {
236: # If this is the correct resource, be sure to
237: # show it by making sure the containing maps
238: # are open.
239:
240: $currentUrlIndex = $counter;
241:
242: for my $map (@{$mapStack}) {
243: if ($condition) {
244: undef $filterHash{$map->map_pc()};
245: } else {
246: $filterHash{$map->map_pc()} = 1;
247: }
248: }
249: $ENV{'form.alreadyHere'} = 1;
250: }
251:
252: # Preprocessing: If we're inlining nav maps into the top-level display,
253: # make sure we show this map!
254: if ($inlineTopLevelMaps && ref($curRes) && $curRes->is_map &&
255: scalar(@{$mapStack}) == 1) {
256: if ($condition) {
257: undef $filterHash{$curRes->map_pc()};
258: } else {
259: $filterHash{$curRes->map_pc()} = 1;
260: }
261: }
262:
263: $curRes = $mapIterator->next();
264: }
265:
266: undef $res; # so we don't accidentally use it later
267: my $indentLevel = 0;
268: my $indentString = "<img src=\"/adm/lonIcons/whitespace1.gif\" width=\"25\" height=\"1\" alt=\"\" border=\"0\" />";
269:
270: my $isNewBranch = 0;
271: my $now = time();
272: my $in24Hours = $now + 24 * 60 * 60;
273: my $displayedHereMarker = 0;
274:
275: # We know the first thing is a BEGIN_MAP (see "$self->{STARTED}"
276: # code in iterator->next), so ignore the first one
277: $mapIterator = $navmap->getIterator(undef, undef, \%filterHash,
278: $condition);
279: $mapIterator->next();
280: $curRes = $mapIterator->next();
281: my $deltadepth = 0;
282: $depth = 1;
283:
284: my @backgroundColors = ("#FFFFFF", "#F6F6F6");
285: my $rowNum = 0;
286:
287: $counter = 0;
288:
289: while ($depth > 0) {
290: # If we're in a new style course, and this is a BEGIN_MAP, END_MAP, or
291: # map resource and the stack depth is only one, just plain ignore this resource
292: # entirely. (This has the effect of inlining the resources in that map
293: # in the nav map.)
294: if ($inlineTopLevelMaps && scalar(@{$mapIterator->getStack()}) == 1 &&
295: ref($curRes) && $curRes->is_map()) {
296: # We let the normal depth stuff occur, but we need to shift everything
297: # over by one to the left to make it look right.
298: $deltadepth = -1;
299: $curRes = $mapIterator->next();
300: next;
301: }
302:
303: if ($curRes == $mapIterator->BEGIN_MAP() ||
304: $curRes == $mapIterator->BEGIN_BRANCH()) {
305: $indentLevel++;
306: }
307: if ($curRes == $mapIterator->END_MAP() ||
308: $curRes == $mapIterator->END_BRANCH()) {
309: $indentLevel--;
310: }
311: if ($curRes == $mapIterator->BEGIN_BRANCH()) {
312: $isNewBranch = 1;
313: }
314: if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
315: if ($curRes == $mapIterator->END_MAP()) { $depth--; }
316:
317: if (ref($curRes)) { $counter++; }
318:
319: if ($depth == 1) { $deltadepth = 0; } # we're done shifting, because we're
320: # out of the inlined map
321:
322: # Is this resource being blotted out?
323: if (ref($curRes) && !advancedUser() && $curRes->randomout()) {
324: $curRes = $mapIterator->next();
325: next; # and totally ignore this resource
326: }
327:
328: if (ref($curRes) && $curRes->src()) {
329:
330: # Step one: Decide which parts to show
331: my @parts = @{$curRes->parts()};
332: my $multipart = scalar(@parts) > 1;
333: my $condensed = 0;
334:
335: if ($curRes->is_problem()) {
336: # Is it multipart?
337:
338: if ($multipart) {
339: # If it's multipart, see if part 0 is "open"
340: # if it is, display all parts, if it isn't,
341: # just display first
342: if (!$curRes->opendate("0")) {
343: @parts = ("0"); # just display the zero-th part
344: $condensed = 1;
345: } else {
346: # Otherwise, only display part 0 if we want to
347: # attach feedback or email information to it
348: if ($curRes->hasDiscussion() || $curRes->getFeedback()) {
349: shift @parts;
350: } else {
351: # If there's discussion or feedback, that counts
352: # as a difference, so display the parts.
353:
354: # Now, we decide whether to condense the
355: # parts due to similarity
356: my $status = $curRes->status($parts[1]);
357: my $due = $curRes->duedate($parts[1]);
358: my $open = $curRes->opendate($parts[1]);
359: my $statusAllSame = 1;
360: my $dueAllSame = 1;
361: my $openAllSame = 1;
362: for (my $i = 2; $i < scalar(@parts); $i++) {
363: if ($curRes->status($parts[$i]) != $status){
364: $statusAllSame = 0;
365: }
366: if ($curRes->duedate($parts[$i]) != $due ) {
367: $dueAllSame = 0;
368: }
369: if ($curRes->opendate($parts[$i]) != $open) {
370: $openAllSame = 0;
371: }
372: }
373:
374: # $allSame is true if all the statuses were
375: # the same. Now, if they are all the same and
376: # match one of the statuses to condense, or they
377: # are all open with the same due date, or they are
378: # all OPEN_LATER with the same open date, display the
379: # status of the first non-zero part (to get the 'correct'
380: # status right, since 0 is never 'correct' or 'open').
381: if (($statusAllSame && defined($condenseStatuses{$status})) ||
382: ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
383: ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
384: @parts = ($parts[1]);
385: $condensed = 1;
386: }
387: }
388: }
389: }
390:
391: } else {
392: $parts[0] = "0"; # this is to get past foreach loop below
393: # you can consider a non-problem resource as a resource
394: # with only one part without loss
395: }
396:
397: # Is it a multipart problem with a single part, now in
398: # @parts with "0" filtered out? If so, forget it's a multi-part
399: # problem and treat it like a single-part problem.
400: if ( scalar(@parts) == 1 ) {
401: $multipart = 0;
402: }
403:
404: # Display one part, in event of network error.
405: # If this is a single part, we can at least show the correct
406: # status, but if it's multipart, we're lost.
407: if ($curRes->{RESOURCE_ERROR}) {
408: @parts = ("0");
409: }
410:
411: # Step two: Show the parts
412: foreach my $part (@parts) {
413:
414: my $deltalevel = 0; # for inserting the branch icon
415: my $nonLinkedText = ""; # unlinked stuff after title
416:
417: # For each thing we're displaying...
418:
419: my $stack = $mapIterator->getStack();
420: my $src = getLinkForResource($stack);
421:
422: my $srcHasQuestion = $src =~ /\?/;
423: my $link = $src.
424: ($srcHasQuestion?'&':'?') .
425: 'symb='.&Apache::lonnet::escape($curRes->symb()).
426: '"';
427: my $title = $curRes->title();
428: if (!$title) {
429: $title = $curRes->src();
430: $title = substr ($title, rindex($title, "/") + 1);
431: }
432: my $partLabel = "";
433: my $newBranchText = "";
434:
435: # If this is a new branch, label it so
436: # (temporary, this should be an icon w/ alt text)
437: if ($isNewBranch) {
438: $newBranchText = "<img src=\"/adm/lonIcons/branch.gif\" border=\"0\">";
439: $isNewBranch = 0;
440: $deltalevel = 1;
441: }
442:
443: # links to open and close the folders
444: my $linkopen = "<a href=\"$link\">";
445: my $linkclose = "</a>";
446:
447: my $icon = "<img src=\"/adm/lonIcons/html.gif\" alt=\"\" border=\"0\" />";
448: if ($curRes->is_problem()) {
449: if ($part eq "0" || $condensed) {
450: $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border=\"0\" />';
451: } else {
452: $icon = $indentString;
453: }
454: }
455:
456: # Display the correct icon, link to open or shut map
457: if ($curRes->is_map()) {
458: my $mapId = $curRes->map_pc();
459: my $nowOpen = (!defined($filterHash{$mapId}));
460: if ($condition) {$nowOpen = !$nowOpen;}
461: $icon = $nowOpen ?
462: "navmap.folder.closed.gif" : "navmap.folder.open.gif";
463: $icon = "<img src=\"/adm/lonIcons/$icon\" alt=\"\" border=\"0\" />";
464: $linkopen = "<a href=\"/adm/navmaps?filter=";
465: $linkopen .= ($nowOpen xor $condition) ?
466: addToFilter(\%filterHash, $mapId) :
467: removeFromFilter(\%filterHash, $mapId);
468: $linkopen .= "&condition=$condition&$queryAdd\">";
469: $linkclose = "</a>";
470:
471: }
472:
473: my $colorizer = "";
474: my $color;
475: if ($curRes->is_problem()) {
476: my $status = $curRes->status($part);
477: $color = $colormap{$status};
478:
479: # Special case in the navmaps: If in less then
480: # 24 hours, give it a bit of urgency
481: if (($status == $curRes->OPEN() || $status == $curRes->ATTEMPTED() ||
482: $status == $curRes->TRIES_LEFT())
483: && $curRes->duedate() &&
484: $curRes->duedate() < time()+(24*60*60) &&
485: $curRes->duedate() > time()) {
486: $color = $hurryUpColor;
487: }
488: # Special case: If this is the last try, and there is
489: # more then one available, and it's not due yet, give a bit of urgency
490: my $tries = $curRes->tries($part);
491: my $maxtries = $curRes->maxtries($part);
492: if ($tries && $maxtries && $maxtries > 1 &&
493: $maxtries - $tries == 1 && $curRes->duedate() &&
494: $curRes->duedate() > time()) {
495: $color = $hurryUpColor;
496: }
497: if ($color ne "") {
498: $colorizer = "bgcolor=\"$color\"";
499: }
500: }
501:
502: if ($curRes->randomout()) {
503: $nonLinkedText .= ' <i>(hidden)</i> ';
504: }
505:
506: $rowNum++;
507: my $backgroundColor = $backgroundColors[$rowNum % scalar(@backgroundColors)];
508:
509: # FIRST COL: The resource indentation, branch icon, name, and anchor
510: $r->print(" <tr bgcolor=\"$backgroundColor\"><td align=\"left\" valign=\"center\" width=\"60%\">\n");
511:
512: # anchor for current resource... - 5 is deliberate: If it's that
513: # high on the screen, don't bother focusing on it. Also this will
514: # print multiple anchors if this is an expanded multi-part problem...
515: # who cares?
516: if ($counter == $currentUrlIndex - 5) {
517: $r->print('<a name="current" />');
518: }
519:
520: # print indentation
521: for (my $i = 0; $i < $indentLevel - $deltalevel + $deltadepth; $i++) {
522: $r->print($indentString);
523: }
524:
525: $r->print(" ${newBranchText}${linkopen}$icon${linkclose}\n");
526:
527: my $curMarkerBegin = "";
528: my $curMarkerEnd = "";
529:
530: # Is this the current resource?
531: if ($curRes->src() eq $currenturl && !$displayedHereMarker) {
532: $curMarkerBegin = '<a name="curloc" /><font color="red" size="+2">> </font>';
533: $curMarkerEnd = '<font color="red" size="+2"> <</font>';
534: $displayedHereMarker = 1;
535: }
536:
537: if ($curRes->is_problem() && $part ne "0" && !$condensed) {
538: $partLabel = " (Part $part)";
539: $title = "";
540: }
541: if ($multipart && $condensed) {
542: $nonLinkedText .= ' (' . $curRes->countParts() . ' parts)';
543: }
544:
545: $r->print(" $curMarkerBegin<a href=\"$link\">$title$partLabel</a> $curMarkerEnd $nonLinkedText");
546: #$r->print(" TDV:" . $curRes->{DATA}->{TOP_DOWN_VAL}); # temp
547: #$r->print(" BUV:" . $curRes->{DATA}->{BOT_UP_VAL}); # temp
548: #$r->print(" DD:" . $curRes->{DATA}->{DISPLAY_DEPTH}); # temp
549:
550: if ($curRes->{RESOURCE_ERROR}) {
551: $r->print(&Apache::loncommon::help_open_topic ("Navmap_Host_Down",
552: '<font size="-1">Host down</font>'));
553: }
554:
555: my $discussionHTML = ""; my $feedbackHTML = "";
556:
557: # SECOND COL: Is there text, feedback, errors??
558: if ($curRes->hasDiscussion()) {
559: $discussionHTML = $linkopen .
560: '<img border="0" src="/adm/lonMisc/chat.gif" />' .
561: $linkclose;
562: }
563:
564: if ($curRes->getFeedback()) {
565: my $feedback = $curRes->getFeedback();
566: foreach (split(/\,/, $feedback)) {
567: if ($_) {
568: $feedbackHTML .= ' <a href="/adm/email?display='
569: . &Apache::lonnet::escape($_) . '">'
570: . '<img src="/adm/lonMisc/feedback.gif" '
571: . 'border="0" /></a>';
572: }
573: }
574: }
575:
576: $r->print("<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML </td>");
577:
578: # Is this the first displayed part of a multi-part problem
579: # that has not been condensed, so we should suppress these two
580: # columns?
581: my $firstDisplayed = !$condensed && $multipart && $part eq "0";
582:
583: # THIRD COL: Problem status icon
584: if ($curRes->is_problem() &&
585: !$firstDisplayed) {
586: my $icon = $statusIconMap{$curRes->status($part)};
587: my $alt = $iconAltTags{$icon};
588: if ($icon) {
589: $r->print("<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");
590: } else {
591: $r->print("<td width=\"30\"> </td>\n");
592: }
593: } else { # not problem, no icon
594: $r->print("<td width=\"30\"> </td>\n");
595: }
596:
597: # FOURTH COL: Text description
598: #$r->print("<td $colorizer align=\"right\" valign=\"center\">\n");
599: $r->print("<td align=\"right\" valign=\"center\">\n");
600:
601: if ($curRes->kind() eq "res" &&
602: $curRes->is_problem() &&
603: !$firstDisplayed) {
604: $r->print ("<font color=\"$color\"><b>") if ($color);
605: $r->print (getDescription($curRes, $part));
606: $r->print ("</b></font>") if ($color);
607: }
608: if ($curRes->is_map() && advancedUser() && $curRes->randompick()) {
609: $r->print('(randomly select ' . $curRes->randompick() .')');
610: }
611:
612: $r->print(" </td></tr>\n");
613: }
614: }
615: $curRes = $mapIterator->next();
616: }
617:
618: $r->print("</table></body></html>");
619:
620: $navmap->untieHashes();
621:
622: return OK;
623: }
624:
625: # Convenience functions: Returns a string that adds or subtracts
626: # the second argument from the first hash, appropriate for the
627: # query string that determines which folders to recurse on
628: sub addToFilter {
629: my $hashIn = shift;
630: my $addition = shift;
631: my %hash = %$hashIn;
632: $hash{$addition} = 1;
633:
634: return join (",", keys(%hash));
635: }
636:
637: sub removeFromFilter {
638: my $hashIn = shift;
639: my $subtraction = shift;
640: my %hash = %$hashIn;
641:
642: delete $hash{$subtraction};
643: return join(",", keys(%hash));
644: }
645:
646: # Convenience function: Given a stack returned from getStack on the iterator,
647: # return the correct src() value.
648: # Later, this should add an anchor when we start putting anchors in pages.
649: sub getLinkForResource {
650: my $stack = shift;
651: my $res;
652:
653: # Check to see if there are any pages in the stack
654: foreach $res (@$stack) {
655: if (defined($res) && $res->is_page()) {
656: return $res->src();
657: }
658: }
659:
660: # Failing that, return the src of the last resource that is defined
661: # (when we first recurse on a map, it puts an undefined resource
662: # on the bottom because $self->{HERE} isn't defined yet, and we
663: # want the src for the map anyhow)
664: foreach (@$stack) {
665: if (defined($_)) { $res = $_; }
666: }
667:
668: return $res->src();
669: }
670:
671: # Convenience function: This seperates the logic of how to create
672: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
673: # etc.) into a seperate function. It takes a resource object as the
674: # first parameter, and the part number of the resource as the second.
675: # It's basically a big switch statement on the status of the resource.
676:
677: sub getDescription {
678: my $res = shift;
679: my $part = shift;
680: my $status = $res->status($part);
681:
682: if ($status == $res->NETWORK_FAILURE) { return ""; }
683: if ($status == $res->NOTHING_SET) {
684: return "Not currently assigned.";
685: }
686: if ($status == $res->OPEN_LATER) {
687: return "Open " . timeToHumanString($res->opendate($part));
688: }
689: if ($status == $res->OPEN) {
690: if ($res->duedate($part)) {
691: return "Due " . timeToHumanString($res->duedate($part));
692: } else {
693: return "Open, no due date";
694: }
695: }
696: if ($status == $res->PAST_DUE_ANSWER_LATER) {
697: return "Answer open " . timeToHumanString($res->answerdate($part));
698: }
699: if ($status == $res->PAST_DUE_NO_ANSWER) {
700: return "Was due " . timeToHumanString($res->duedate($part));
701: }
702: if ($status == $res->ANSWER_OPEN) {
703: return "Answer available";
704: }
705: if ($status == $res->EXCUSED) {
706: return "Excused by instructor";
707: }
708: if ($status == $res->ATTEMPTED) {
709: return "Not yet graded.";
710: }
711: if ($status == $res->TRIES_LEFT) {
712: my $tries = $res->tries($part);
713: my $maxtries = $res->maxtries($part);
714: my $triesString = "";
715: if ($tries && $maxtries) {
716: $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
717: if ($maxtries > 1 && $maxtries - $tries == 1) {
718: $triesString = "<b>$triesString</b>";
719: }
720: }
721: if ($res->duedate()) {
722: return "Due " . timeToHumanString($res->duedate($part)) .
723: " $triesString";
724: } else {
725: return "No due date $triesString";
726: }
727: }
728: }
729:
730: sub advancedUser {
731: return $ENV{'user.adv'};
732: }
733:
734:
735: # timeToHumanString takes a time number and converts it to a
736: # human-readable representation, meant to be used in the following
737: # manner:
738: # print "Due $timestring"
739: # print "Open $timestring"
740: # print "Answer available $timestring"
741: # Very, very, very, VERY English-only... goodness help a localizer on
742: # this func...
743: sub timeToHumanString {
744: my ($time) = @_;
745: # zero, '0' and blank are bad times
746: if (!$time) {
747: return 'never';
748: }
749:
750: my $now = time();
751:
752: my @time = localtime($time);
753: my @now = localtime($now);
754:
755: # Positive = future
756: my $delta = $time - $now;
757:
758: my $minute = 60;
759: my $hour = 60 * $minute;
760: my $day = 24 * $hour;
761: my $week = 7 * $day;
762: my $inPast = 0;
763:
764: # Logic in comments:
765: # Is it now? (extremely unlikely)
766: if ( $delta == 0 ) {
767: return "this instant";
768: }
769:
770: if ($delta < 0) {
771: $inPast = 1;
772: $delta = -$delta;
773: }
774:
775: # Is it in the future?
776: if ( $delta > 0 ) {
777: # Is it less then a minute away?
778: my $tense = $inPast ? " ago" : "";
779: my $prefix = $inPast ? "" : "in ";
780: if ( $delta < $minute ) {
781: if ($delta == 1) { return "${prefix}1 second$tense"; }
782: return "$prefix$delta seconds$tense";
783: }
784:
785: # Is it less then an hour away?
786: if ( $delta < $hour ) {
787: # If so, use minutes
788: my $minutes = floor($delta / 60);
789: if ($minutes == 1) { return "${prefix}1 minute$tense"; }
790: return "$prefix$minutes minutes$tense";
791: }
792:
793: # Is it less then 24 hours away? If so,
794: # display hours + minutes
795: if ( $delta < $hour * 24) {
796: my $hours = floor($delta / $hour);
797: my $minutes = floor(($delta % $hour) / $minute);
798: my $hourString = "$hours hours";
799: my $minuteString = ", $minutes minutes";
800: if ($hours == 1) {
801: $hourString = "1 hour";
802: }
803: if ($minutes == 1) {
804: $minuteString = ", 1 minute";
805: }
806: if ($minutes == 0) {
807: $minuteString = "";
808: }
809: return "$prefix$hourString$minuteString$tense";
810: }
811:
812: # Less then 5 days away, display day of the week and
813: # HH:MM
814: if ( $delta < $day * 5 ) {
815: my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
816: $timeStr =~ s/12:00 am/midnight/;
817: $timeStr =~ s/12:00 pm/noon/;
818: return ($inPast ? "last " : "next ") .
819: $timeStr;
820: }
821:
822: # Is it this year?
823: if ( $time[5] == $now[5]) {
824: # Return on Month Day, HH:MM meridian
825: my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
826: $timeStr =~ s/12:00 am/midnight/;
827: $timeStr =~ s/12:00 pm/noon/;
828: return $timeStr;
829: }
830:
831: # Not this year, so show the year
832: my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
833: $timeStr =~ s/12:00 am/midnight/;
834: $timeStr =~ s/12:00 pm/noon/;
835: return $timeStr;
836: }
837: }
838:
839: 1;
840:
841: package Apache::lonnavmaps::navmap;
842:
843: =pod
844:
845: lonnavmaps provides functions and objects for dealing with the compiled course hashes generated when a user enters the course, and also provides the Apache handler for the "Navigation Map" button.
846:
847: =head1 navmap object: Encapsulating the compiled nav map
848:
849: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
850:
851: Most notably it provides a way to navigate the map sensibly and a flexible iterator that makes it easy to write various renderers based on nav maps.
852:
853: You must obtain resource objects through the navmap object.
854:
855: =head2 Methods
856:
857: =over 4
858:
859: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions, genMailDiscussStatus): Binds a new navmap object to the compiled nav map hash and parm hash given as filenames. genCourseAndUserOptions is a flag saying whether the course options and user options hash should be generated. This is for when you are using the parameters of the resources that require them; see documentation in resource object documentation. genMailDiscussStatus causes the nav map to retreive information about the email and discussion status of resources. Returns the navmap object if this is successful, or B<undef> if not. You must check for undef; errors will occur when you try to use the other methods otherwise.
860:
861: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
862:
863: =cut
864:
865: use strict;
866: use GDBM_File;
867:
868: sub new {
869: # magic invocation to create a class instance
870: my $proto = shift;
871: my $class = ref($proto) || $proto;
872: my $self = {};
873:
874: $self->{NAV_HASH_FILE} = shift;
875: $self->{PARM_HASH_FILE} = shift;
876: $self->{GENERATE_COURSE_USER_OPT} = shift;
877: $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
878:
879: # Resource cache stores navmapresource's as we reference them. We generate
880: # them on-demand so we don't pay for creating resources unless we use them.
881: $self->{RESOURCE_CACHE} = {};
882:
883: # Network failure flag, if we accessed the course or user opt and
884: # failed
885: $self->{NETWORK_FAILURE} = 0;
886:
887: # tie the nav hash
888: my %navmaphash;
889: if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
890: &GDBM_READER(), 0640))) {
891: return undef;
892: }
893: $self->{NAV_HASH} = \%navmaphash;
894:
895: my %parmhash;
896: if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
897: &GDBM_READER(), 0640)))
898: {
899: untie $self->{PARM_HASH};
900: return undef;
901: }
902: $self->{PARM_HASH} = \%parmhash;
903: $self->{HASH_TIED} = 1;
904:
905: bless($self);
906:
907: return $self;
908: }
909:
910: sub init {
911: my $self = shift;
912:
913: # If the course opt hash and the user opt hash should be generated,
914: # generate them
915: if ($self->{GENERATE_COURSE_USER_OPT}) {
916: my $uname=$ENV{'user.name'};
917: my $udom=$ENV{'user.domain'};
918: my $uhome=$ENV{'user.home'};
919: my $cid=$ENV{'request.course.id'};
920: my $chome=$ENV{'course.'.$cid.'.home'};
921: my ($cdom,$cnum)=split(/\_/,$cid);
922:
923: my $userprefix=$uname.'_'.$udom.'_';
924:
925: my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
926: unless ($uhome eq 'no_host') {
927: # ------------------------------------------------- Get coursedata (if present)
928: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
929: my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
930: ':resourcedata',$chome);
931: if ($reply!~/^error\:/) {
932: $courserdatas{$cid}=$reply;
933: $courserdatas{$cid.'.last_cache'}=time;
934: }
935: # check to see if network failed
936: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
937: {
938: $self->{NETWORK_FAILURE} = 1;
939: }
940: }
941: foreach (split(/\&/,$courserdatas{$cid})) {
942: my ($name,$value)=split(/\=/,$_);
943: $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
944: &Apache::lonnet::unescape($value);
945: }
946: # --------------------------------------------------- Get userdata (if present)
947: unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
948: my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
949: if ($reply!~/^error\:/) {
950: $userrdatas{$uname.'___'.$udom}=$reply;
951: $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
952: }
953: # check to see if network failed
954: elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
955: {
956: $self->{NETWORK_FAILURE} = 1;
957: }
958: }
959: foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
960: my ($name,$value)=split(/\=/,$_);
961: $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
962: &Apache::lonnet::unescape($value);
963: }
964: $self->{COURSE_OPT} = \%courseopt;
965: $self->{USER_OPT} = \%useropt;
966: }
967: }
968:
969: if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
970: my $cid=$ENV{'request.course.id'};
971: my ($cdom,$cnum)=split(/\_/,$cid);
972:
973: my %emailstatus = &Apache::lonnet::dump('email_status');
974: my $logoutTime = $emailstatus{'logout'};
975: my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
976: $self->{LAST_CHECK} = ($courseLeaveTime > $logoutTime ?
977: $courseLeaveTime : $logoutTime);
978: my %discussiontime = &Apache::lonnet::dump('discussiontimes',
979: $cdom, $cnum);
980: my %feedback=();
981: my %error=();
982: my $keys = &Apache::lonnet::reply('keys:'.
983: $ENV{'user.domain'}.':'.
984: $ENV{'user.name'}.':nohist_email',
985: $ENV{'user.home'});
986:
987: foreach my $msgid (split(/\&/, $keys)) {
988: $msgid=&Apache::lonnet::unescape($msgid);
989: my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
990: if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
991: my ($what,$url)=($1,$2);
992: my %status=
993: &Apache::lonnet::get('email_status',[$msgid]);
994: if ($status{$msgid}=~/^error\:/) {
995: $status{$msgid}='';
996: }
997:
998: if (($status{$msgid} eq 'new') ||
999: (!$status{$msgid})) {
1000: if ($what eq 'Error') {
1001: $error{$url}.=','.$msgid;
1002: } else {
1003: $feedback{$url}.=','.$msgid;
1004: }
1005: }
1006: }
1007: }
1008:
1009: $self->{FEEDBACK} = \%feedback;
1010: $self->{ERROR_MSG} = \%error; # what is this? JB
1011: $self->{DISCUSSION_TIME} = \%discussiontime;
1012: $self->{EMAIL_STATUS} = \%emailstatus;
1013:
1014: }
1015:
1016: $self->{PARM_CACHE} = {};
1017: }
1018:
1019: # Checks to see if coursemap is defined, matching test in old lonnavmaps
1020: sub courseMapDefined {
1021: my $self = shift;
1022: my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
1023:
1024: my $firstres = $self->{NAV_HASH}->{"map_start_$uri"};
1025: my $lastres = $self->{NAV_HASH}->{"map_finish_$uri"};
1026: return $firstres && $lastres;
1027: }
1028:
1029: sub getIterator {
1030: my $self = shift;
1031: my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
1032: shift, undef, shift,
1033: $ENV{'form.direction'});
1034: return $iterator;
1035: }
1036:
1037: # unties the hash when done
1038: sub untieHashes {
1039: my $self = shift;
1040: untie %{$self->{NAV_HASH}} if ($self->{HASH_TIED});
1041: untie %{$self->{PARM_HASH}} if ($self->{HASH_TIED});
1042: $self->{HASH_TIED} = 0;
1043: }
1044:
1045: # when the object is destroyed, be sure to untie all the hashes we tied.
1046: sub DESTROY {
1047: my $self = shift;
1048: $self->untieHashes();
1049: }
1050:
1051: # Private function: Does the given resource (as a symb string) have
1052: # current discussion? Returns 0 if chat/mail data not extracted.
1053: sub hasDiscussion {
1054: my $self = shift;
1055: my $symb = shift;
1056: if (!defined($self->{DISCUSSION_TIME})) { return 0; }
1057:
1058: return $self->{DISCUSSION_TIME}->{$symb} >
1059: $self->{LAST_CHECK};
1060: }
1061:
1062: # Private function: Does the given resource (as a symb string) have
1063: # current feedback? Returns the string in the feedback hash, which
1064: # will be false if it does not exist.
1065: sub getFeedback {
1066: my $self = shift;
1067: my $symb = shift;
1068:
1069: if (!defined($self->{FEEDBACK})) { return ""; }
1070:
1071: return $self->{FEEDBACK}->{$symb};
1072: }
1073:
1074: =pod
1075:
1076: =item * B<getById>(id): Based on the ID of the resource (1.1, 3.2, etc.), get a resource object for that resource. This method, or other methods that use it (as in the resource object) is the only proper way to obtain a resource object.
1077:
1078: =cut
1079:
1080: # The strategy here is to cache the resource objects, and only construct them
1081: # as we use them. The real point is to prevent reading any more from the tied
1082: # hash then we have to, which should hopefully alleviate speed problems.
1083: # Caching is just an incidental detail I throw in because it makes sense.
1084:
1085: sub getById {
1086: my $self = shift;
1087: my $id = shift;
1088:
1089: if (defined ($self->{RESOURCE_CACHE}->{$id}))
1090: {
1091: return $self->{RESOURCE_CACHE}->{$id};
1092: }
1093:
1094: # resource handles inserting itself into cache.
1095: return Apache::lonnavmaps::resource->new($self, $id);
1096: }
1097:
1098: =pod
1099:
1100: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
1101:
1102: =cut
1103:
1104: sub firstResource {
1105: my $self = shift;
1106: my $firstResource = $self->{NAV_HASH}->{'map_start_' .
1107: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
1108: return $self->getById($firstResource);
1109: }
1110:
1111: =pod
1112:
1113: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
1114:
1115: =cut
1116:
1117: sub finishResource {
1118: my $self = shift;
1119: my $firstResource = $self->{NAV_HASH}->{'map_finish_' .
1120: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
1121: return $self->getById($firstResource);
1122: }
1123:
1124: # -------------------------------------------- Figure out a cascading parameter
1125: #
1126: # For this function to work
1127: #
1128: # * parmhash needs to be tied
1129: # * courseopt and useropt need to be initialized for this user and course
1130: #
1131:
1132: sub parmval {
1133: my $self = shift;
1134: my ($what,$symb)=@_;
1135: my $hashkey = $what."|||".$symb;
1136:
1137: if (defined($self->{PARM_CACHE}->{$hashkey})) {
1138: return $self->{PARM_CACHE}->{$hashkey};
1139: }
1140:
1141: my $result = $self->parmval_real($what, $symb);
1142: $self->{PARM_CACHE}->{$hashkey} = $result;
1143: return $result;
1144: }
1145:
1146: sub parmval_real {
1147: my $self = shift;
1148: my ($what,$symb) = @_;
1149:
1150: my $cid=$ENV{'request.course.id'};
1151: my $csec=$ENV{'request.course.sec'};
1152: my $uname=$ENV{'user.name'};
1153: my $udom=$ENV{'user.domain'};
1154:
1155: unless ($symb) { return ''; }
1156: my $result='';
1157:
1158: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
1159:
1160: # ----------------------------------------------------- Cascading lookup scheme
1161: my $rwhat=$what;
1162: $what=~s/^parameter\_//;
1163: $what=~s/\_/\./;
1164:
1165: my $symbparm=$symb.'.'.$what;
1166: my $mapparm=$mapname.'___(all).'.$what;
1167: my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
1168:
1169: my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
1170: my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
1171: my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
1172:
1173: my $courselevel= $usercourseprefix.'.'.$what;
1174: my $courselevelr=$usercourseprefix.'.'.$symbparm;
1175: my $courselevelm=$usercourseprefix.'.'.$mapparm;
1176:
1177: my $useropt = $self->{USER_OPT};
1178: my $courseopt = $self->{COURSE_OPT};
1179: my $parmhash = $self->{PARM_HASH};
1180:
1181: # ---------------------------------------------------------- first, check user
1182: if ($uname and defined($useropt)) {
1183: if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
1184: if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
1185: if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
1186: }
1187:
1188: # ------------------------------------------------------- second, check course
1189: if ($csec and defined($courseopt)) {
1190: if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
1191: if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
1192: if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
1193: }
1194:
1195: if (defined($courseopt)) {
1196: if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
1197: if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
1198: if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
1199: }
1200:
1201: # ----------------------------------------------------- third, check map parms
1202:
1203: my $thisparm=$$parmhash{$symbparm};
1204: if (defined($thisparm)) { return $thisparm; }
1205:
1206: # ----------------------------------------------------- fourth , check default
1207:
1208: my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
1209: if (defined($default)) { return $default}
1210:
1211: # --------------------------------------------------- fifth , cascade up parts
1212:
1213: my ($space,@qualifier)=split(/\./,$rwhat);
1214: my $qualifier=join('.',@qualifier);
1215: unless ($space eq '0') {
1216: my ($part,$id)=split(/\_/,$space);
1217: if ($id) {
1218: my $partgeneral=$self->parmval($part.".$qualifier",$symb);
1219: if (defined($partgeneral)) { return $partgeneral; }
1220: } else {
1221: my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
1222: if (defined($resourcegeneral)) { return $resourcegeneral; }
1223: }
1224: }
1225: return '';
1226: }
1227:
1228:
1229: 1;
1230:
1231: package Apache::lonnavmaps::iterator;
1232:
1233: # This package must precede "navmap" because "navmap" uses it. In
1234: # order to keep the documentation order straight, the iterator is documented
1235: # after the navmap object.
1236:
1237: =pod
1238:
1239: =back
1240:
1241: =head1 navmap Iterator
1242:
1243: An I<iterator> encapsulates the logic required to traverse a data structure. navmap uses an iterator to traverse the course map according to the criteria you wish to use.
1244:
1245: To obtain an iterator, call the B<getIterator>() function of a B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator directly.) This will return a reference to the iterator:
1246:
1247: C<my $resourceIterator = $navmap-E<gt>getIterator();>
1248:
1249: To get the next thing from the iterator, call B<next>:
1250:
1251: C<my $nextThing = $resourceIterator-E<gt>next()>
1252:
1253: getIterator behaves as follows:
1254:
1255: =over 4
1256:
1257: =item B<getIterator>(firstResource, finishResource, filterHash, condition, direction): All parameters are optional. firstResource is a resource reference corresponding to where the iterator should start. It defaults to navmap->firstResource() for the corresponding nav map. finishResource corresponds to where you want the iterator to end, defaulting to navmap->finishResource(). filterHash is a hash used as a set containing strings representing the resource IDs, defaulting to empty. Condition is a 1 or 0 that sets what to do with the filter hash: If a 0, then only resource that exist IN the filterHash will be recursed on. If it is a 1, only resources NOT in the filterHash will be recursed on. Defaults to 0, which is to say, do not recurse unless explicitly asked to. Direction specifies which direction to recurse, either FORWARD or BACKWARD, with FORWARD being default.
1258:
1259: Thus, by default, all resources will be shown. Change the condition to a 1 without changing the hash, and only the top level of the map will be shown. Changing the condition to 1 and including some values in the hash will allow you to selectively examine parts of the navmap, while leaving it on 0 and adding things to the hash will allow you to selectively ignore parts of the nav map. See the handler code for examples: By default, the condition is 0 and all folders are closed unless explicitly opened. Clicking "Show All Resources" will use a condition of 1 and an empty filterHash, resulting in all resources being shown.
1260:
1261: The iterator will return either a reference to a resource object, or a token representing something in the map, such as the beginning of a new branch. The possible tokens are:
1262:
1263: =over 4
1264:
1265: =item * BEGIN_MAP: A new map is being recursed into. This is returned I<after> the map resource itself is returned.
1266:
1267: =item * END_MAP: The map is now done.
1268:
1269: =item * BEGIN_BRANCH: A branch is now starting. The next resource returned will be the first in that branch.
1270:
1271: =item * END_BRANCH: The branch is now done.
1272:
1273: =back
1274:
1275: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_MAP.
1276:
1277: =back
1278:
1279: =cut
1280:
1281: # Here are the tokens for the iterator:
1282:
1283: sub BEGIN_MAP { return 1; } # begining of a new map
1284: sub END_MAP { return 2; } # end of the map
1285: sub BEGIN_BRANCH { return 3; } # beginning of a branch
1286: sub END_BRANCH { return 4; } # end of a branch
1287: sub FORWARD { return 1; } # go forward
1288: sub BACKWARD { return 2; }
1289:
1290: sub min {
1291: (my $a, my $b) = @_;
1292: if ($a < $b) { return $a; } else { return $b; }
1293: }
1294:
1295: sub new {
1296: # magic invocation to create a class instance
1297: my $proto = shift;
1298: my $class = ref($proto) || $proto;
1299: my $self = {};
1300:
1301: $self->{NAV_MAP} = shift;
1302: return undef unless ($self->{NAV_MAP});
1303:
1304: # Handle the parameters
1305: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
1306: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
1307:
1308: # If the given resources are just the ID of the resource, get the
1309: # objects
1310: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
1311: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
1312: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
1313: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
1314:
1315: $self->{FILTER} = shift;
1316:
1317: # A hash, used as a set, of resource already seen
1318: $self->{ALREADY_SEEN} = shift;
1319: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1320: $self->{CONDITION} = shift;
1321:
1322: # Now, we need to pre-process the map, by walking forward and backward
1323: # over the parts of the map we're going to look at.
1324:
1325: # The processing steps are exactly the same, except for a few small
1326: # changes, so I bundle those up in the following list of two elements:
1327: # (direction_to_iterate, VAL_name, next_resource_method_to_call,
1328: # first_resource).
1329: # This prevents writing nearly-identical code twice.
1330: my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext',
1331: 'FIRST_RESOURCE'],
1332: [BACKWARD(), 'BOT_UP_VAL', 'getPrevious',
1333: 'FINISH_RESOURCE'] );
1334:
1335: my $maxDepth = 0; # tracks max depth
1336:
1337: foreach my $pass (@iterations) {
1338: my $direction = $pass->[0];
1339: my $valName = $pass->[1];
1340: my $nextResourceMethod = $pass->[2];
1341: my $firstResourceName = $pass->[3];
1342:
1343: my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP},
1344: $self->{FIRST_RESOURCE},
1345: $self->{FINISH_RESOURCE},
1346: {}, undef, 0, $direction);
1347:
1348: # prime the recursion
1349: $self->{$firstResourceName}->{DATA}->{$valName} = 0;
1350: my $depth = 0;
1351: $iterator->next();
1352: my $curRes = $iterator->next();
1353: while ($depth > -1) {
1354: if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
1355: if ($curRes == $iterator->END_MAP()) { $depth--; }
1356:
1357: if (ref($curRes)) {
1358: my $resultingVal = $curRes->{DATA}->{$valName};
1359: my $nextResources = $curRes->$nextResourceMethod();
1360: my $resourceCount = scalar(@{$nextResources});
1361:
1362: if ($resourceCount == 1) {
1363: my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
1364: $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
1365: }
1366:
1367: if ($resourceCount > 1) {
1368: foreach my $res (@{$nextResources}) {
1369: my $current = $res->{DATA}->{$valName} || 999999999;
1370: $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
1371: }
1372: }
1373: }
1374: if (ref($curRes) && $curRes->is_map() && $direction == FORWARD()) {
1375: my $firstResource = $curRes->map_start();
1376: my $finishResource = $curRes->map_finish();
1377: my $newIterator = Apache::lonnavmaps::iterator->new($self->{NAV_MAP},
1378: $firstResource,
1379: $finishResource,
1380: $self->{FILTER},
1381: $self->{ALREADY_SEEN},
1382: $self->{CONDITION});
1383: }
1384:
1385: # Assign the final val
1386: if (ref($curRes) && $direction == BACKWARD()) {
1387: my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
1388: $curRes->{DATA}->{BOT_UP_VAL});
1389:
1390: $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
1391: if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
1392: }
1393: $curRes = $iterator->next();
1394: }
1395: }
1396:
1397: # Set up some bookkeeping information.
1398: $self->{CURRENT_DEPTH} = 0;
1399: $self->{MAX_DEPTH} = $maxDepth;
1400: $self->{STACK} = [];
1401: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1402:
1403: for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
1404: push @{$self->{STACK}}, [];
1405: }
1406:
1407: # Prime the recursion w/ the first resource
1408: push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
1409: $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
1410:
1411: bless ($self);
1412:
1413: return $self;
1414: }
1415:
1416: sub next {
1417: my $self = shift;
1418:
1419: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1420: # grab the next from the recursive iterator
1421: my $next = $self->{RECURSIVE_ITERATOR}->next();
1422:
1423: # is it a begin or end map? If so, update the depth
1424: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
1425: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
1426:
1427: # Are we back at depth 0? If so, stop recursing
1428: if ($self->{RECURSIVE_DEPTH} == 0) {
1429: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1430: }
1431:
1432: return $next;
1433: }
1434:
1435: if (defined($self->{FORCE_NEXT})) {
1436: my $tmp = $self->{FORCE_NEXT};
1437: $self->{FORCE_NEXT} = undef;
1438: return $tmp;
1439: }
1440:
1441: # Have we not yet begun? If not, return BEGIN_MAP and
1442: # remember we've started.
1443: if ( !$self->{STARTED} ) {
1444: $self->{STARTED} = 1;
1445: return $self->BEGIN_MAP();
1446: }
1447:
1448: # Here's the guts of the iterator.
1449:
1450: # Find the next resource, if any.
1451: my $found = 0;
1452: my $i = $self->{MAX_DEPTH};
1453: my $newDepth;
1454: my $here;
1455: while ( $i >= 0 && !$found ) {
1456: if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) {
1457: $here = $self->{HERE} = shift @{$self->{STACK}->[$i]};
1458: $found = 1;
1459: $newDepth = $i;
1460: }
1461: $i--;
1462: }
1463:
1464: # If we still didn't find anything, we're done.
1465: if ( !$found ) {
1466: # We need to get back down to the correct branch depth
1467: if ( $self->{CURRENT_DEPTH} > 0 ) {
1468: $self->{CURRENT_DEPTH}--;
1469: return END_BRANCH();
1470: } else {
1471: return END_MAP();
1472: }
1473: }
1474:
1475: # Get to the right level
1476: if ( $self->{CURRENT_DEPTH} > $newDepth ) {
1477: push @{$self->{STACK}->[$newDepth]}, $here;
1478: $self->{CURRENT_DEPTH}--;
1479: return END_BRANCH();
1480: }
1481: if ( $self->{CURRENT_DEPTH} < $newDepth) {
1482: push @{$self->{STACK}->[$newDepth]}, $here;
1483: $self->{CURRENT_DEPTH}++;
1484: return BEGIN_BRANCH();
1485: }
1486:
1487: # If we made it here, we have the next resource, and we're at the
1488: # right branch level. So let's examine the resource for where
1489: # we can get to from here.
1490:
1491: # So we need to look at all the resources we can get to from here,
1492: # categorize them if we haven't seen them, remember if we have a new
1493: my $nextUnfiltered = $here->getNext();
1494:
1495: for (@$nextUnfiltered) {
1496: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1497: push @{$self->{STACK}->[$_->{DATA}->{DISPLAY_DEPTH}]}, $_;
1498: $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
1499: }
1500: }
1501:
1502: # That ends the main iterator logic. Now, do we want to recurse
1503: # down this map (if this resource is a map)?
1504: if ($self->{HERE}->is_map() &&
1505: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
1506: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
1507: my $firstResource = $self->{HERE}->map_start();
1508: my $finishResource = $self->{HERE}->map_finish();
1509:
1510: $self->{RECURSIVE_ITERATOR} =
1511: Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
1512: $finishResource, $self->{FILTER},
1513: $self->{ALREADY_SEEN}, $self->{CONDITION});
1514: }
1515:
1516: return $self->{HERE};
1517:
1518: }
1519:
1520: =pod
1521:
1522: The other method available on the iterator is B<getStack>, which returns an array populated with the current 'stack' of maps, as references to the resource objects. Example: This is useful when making the navigation map, as we need to check whether we are under a page map to see if we need to link directly to the resource, or to the page. The first elements in the array will correspond to the top of the stack (most inclusive map).
1523:
1524: =cut
1525:
1526: sub getStack {
1527: my $self=shift;
1528:
1529: my @stack;
1530:
1531: $self->populateStack(\@stack);
1532:
1533: return \@stack;
1534: }
1535:
1536: # Private method: Calls the iterators recursively to populate the stack.
1537: sub populateStack {
1538: my $self=shift;
1539: my $stack = shift;
1540:
1541: push @$stack, $self->{HERE} if ($self->{HERE});
1542:
1543: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1544: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
1545: }
1546: }
1547:
1548: 1;
1549:
1550: package Apache::lonnavmaps::DFSiterator;
1551:
1552: # UNDOCUMENTED: This is a private library, it should not generally be used
1553: # by the outside world. What it does is walk through the nav map in a
1554: # depth-first fashion. This is not appropriate for most uses, but it is
1555: # used by the main iterator for pre-processing. It also is able to isolate
1556: # much of the complexity of the main iterator, so the main iterator is much
1557: # simpler.
1558: # There is no real benefit in merging the main iterator and this one into one class...
1559: # all the logic in DFSiterator would need to be replicated, you gain no performance,
1560: # at best, you just make one massively complicated iterator in place of two
1561: # somewhat complicated ones. ;-) - Jeremy
1562:
1563: # Here are the tokens for the iterator, replicated from iterator for convenience:
1564:
1565: sub BEGIN_MAP { return 1; } # begining of a new map
1566: sub END_MAP { return 2; } # end of the map
1567: sub BEGIN_BRANCH { return 3; } # beginning of a branch
1568: sub END_BRANCH { return 4; } # end of a branch
1569: sub FORWARD { return 1; } # go forward
1570: sub BACKWARD { return 2; }
1571:
1572: # Params: nav map, start resource, end resource, filter, condition,
1573: # already seen hash ref
1574:
1575: sub new {
1576: # magic invocation to create a class instance
1577: my $proto = shift;
1578: my $class = ref($proto) || $proto;
1579: my $self = {};
1580:
1581: $self->{NAV_MAP} = shift;
1582: return undef unless ($self->{NAV_MAP});
1583:
1584: # Handle the parameters
1585: $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
1586: $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
1587:
1588: # If the given resources are just the ID of the resource, get the
1589: # objects
1590: if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} =
1591: $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
1592: if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} =
1593: $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
1594:
1595: $self->{FILTER} = shift;
1596:
1597: # A hash, used as a set, of resource already seen
1598: $self->{ALREADY_SEEN} = shift;
1599: if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1600: $self->{CONDITION} = shift;
1601: $self->{DIRECTION} = shift || FORWARD();
1602:
1603: # Flag: Have we started yet? If not, the first action is to return BEGIN_MAP.
1604: $self->{STARTED} = 0;
1605:
1606: # Should we continue calling the recursive iterator, if any?
1607: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1608: # The recursive iterator, if any
1609: $self->{RECURSIVE_ITERATOR} = undef;
1610: # Are we recursing on a map, or a branch?
1611: $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
1612: # And the count of how deep it is, so that this iterator can keep track of
1613: # when to pick back up again.
1614: $self->{RECURSIVE_DEPTH} = 0;
1615:
1616: # For keeping track of our branches, we maintain our own stack
1617: $self->{BRANCH_STACK} = [];
1618: # If the size shrinks, we exhausted a branch
1619: $self->{BRANCH_STACK_SIZE} = 0;
1620: $self->{BRANCH_DEPTH} = 0;
1621:
1622: # For returning two things in a forced sequence
1623: $self->{FORCE_NEXT} = undef;
1624:
1625: # Start with the first resource
1626: if ($self->{DIRECTION} == FORWARD) {
1627: push @{$self->{BRANCH_STACK}}, $self->{FIRST_RESOURCE};
1628: } else {
1629: push @{$self->{BRANCH_STACK}}, $self->{FINISH_RESOURCE};
1630: }
1631: $self->{BRANCH_STACK_SIZE} = 1;
1632:
1633: bless($self);
1634: return $self;
1635: }
1636:
1637: # Note... this function is *touchy*. I strongly recommend tracing
1638: # through it with the debugger a few times on a non-trivial map before
1639: # modifying it. Order is *everything*.
1640: sub next {
1641: my $self = shift;
1642:
1643: # Iterator logic goes here
1644:
1645: # Are we using a recursive iterator? If so, pull from that and
1646: # watch the depth; we want to resume our level at the correct time.
1647: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1648: # grab the next from the recursive iterator
1649: my $next = $self->{RECURSIVE_ITERATOR}->next();
1650:
1651: # is it a begin or end map? Update depth if so
1652: if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
1653: if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
1654:
1655: # Are we back at depth 0? If so, stop recursing.
1656: if ($self->{RECURSIVE_DEPTH} == 0) {
1657: $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1658: }
1659:
1660: return $next;
1661: }
1662:
1663: # Is this return value pre-determined?
1664: if (defined($self->{FORCE_NEXT})) {
1665: my $tmp = $self->{FORCE_NEXT};
1666: $self->{FORCE_NEXT} = undef;
1667: return $tmp;
1668: }
1669:
1670: # Is there a current resource to grab? If not, then return
1671: # END_BRANCH and END_MAP in succession.
1672: if (scalar(@{$self->{BRANCH_STACK}}) == 0) {
1673: if ($self->{BRANCH_DEPTH} > 0) {
1674: $self->{FORCE_NEXT} = $self->END_MAP();
1675: $self->{BRANCH_DEPTH}--;
1676: return $self->END_BRANCH();
1677: } else {
1678: return $self->END_MAP();
1679: }
1680: }
1681:
1682: # Have we not yet begun? If not, return BEGIN_MAP and
1683: # remember that we've started.
1684: if ( !$self->{STARTED} ) {
1685: $self->{STARTED} = 1;
1686: return $self->BEGIN_MAP;
1687: }
1688:
1689: # Did the branch stack shrink since last run? If so,
1690: # we exhausted a branch last time, therefore, we're about
1691: # to start a new one. (We know because we already checked to see
1692: # if the stack was empty.)
1693: if ( scalar (@{$self->{BRANCH_STACK}}) < $self->{BRANCH_STACK_SIZE}) {
1694: $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
1695: $self->{BRANCH_DEPTH}++;
1696: return $self->BEGIN_BRANCH();
1697: }
1698:
1699: # Remember the size for comparision next time.
1700: $self->{BRANCH_STACK_SIZE} = scalar(@{$self->{BRANCH_STACK}});
1701:
1702: # If the next resource we mean to return is going to need
1703: # a lower branch level, terminate branches until we get
1704: # there.
1705:
1706: # Get the next resource in the branch
1707: $self->{HERE} = pop @{$self->{BRANCH_STACK}};
1708:
1709: # Are we at the right depth? If not, close a branch and return
1710: # the current resource onto the branch stack
1711: # Note: There seems to be some bugs here, so don't rely
1712: # on this, use the real iterator instead.
1713: if (defined($self->{HERE}->{DATA}->{ITERATOR_DEPTH})
1714: && $self->{HERE}->{DATA}->{ITERATOR_DEPTH} <
1715: $self->{BRANCH_DEPTH} ) {
1716: $self->{BRANCH_DEPTH}--;
1717: # return it so we can pick it up eventually
1718: push @{$self->{BRANCH_STACK}}, $self->{HERE};
1719: return $self->END_BRANCH();
1720: }
1721:
1722: # We always return it after this point and never before
1723: # (proof: look at just the return statements), so we
1724: # remember that we've seen this.
1725: $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
1726:
1727: # Get the next possible resources
1728: my $nextUnfiltered;
1729: if ($self->{DIRECTION} == FORWARD()) {
1730: $nextUnfiltered = $self->{HERE}->getNext();
1731: } else {
1732: $nextUnfiltered = $self->{HERE}->getPrevious();
1733: }
1734: my $next = [];
1735:
1736: # filter the next possibilities to remove things we've
1737: # already seen. Also, remember what branch depth they should
1738: # be displayed at, since there's no other reliable way to tell.
1739: foreach (@$nextUnfiltered) {
1740: if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1741: push @$next, $_;
1742: $_->{DATA}->{ITERATOR_DEPTH} =
1743: $self->{BRANCH_DEPTH} + 1;
1744: }
1745: }
1746:
1747: # Handle branch cases:
1748: # Nothing is available next: BRANCH_END
1749: # 1 thing next: standard non-branch
1750: # 2+ things next: have some branches
1751: my $nextCount = scalar(@$next);
1752: if ($nextCount == 0) {
1753: # Return this and on the next run, close the branch up if we're
1754: # in a branch
1755: if ($self->{BRANCH_DEPTH} > 0 ) {
1756: $self->{FORCE_NEXT} = $self->END_BRANCH();
1757: $self->{BRANCH_DEPTH}--;
1758: }
1759: }
1760:
1761: while (@$next) {
1762: # copy the next possibilities over to the branch stack
1763: # in the right order
1764: push @{$self->{BRANCH_STACK}}, shift @$next;
1765: }
1766:
1767: if ($nextCount >= 2) {
1768: $self->{FORCE_NEXT} = $self->BEGIN_BRANCH();
1769: $self->{BRANCH_DEPTH}++;
1770: return $self->{HERE};
1771: }
1772:
1773: # If this is a map and we want to recurse down it... (not filtered out)
1774: if ($self->{HERE}->is_map() &&
1775: (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
1776: $self->{RECURSIVE_ITERATOR_FLAG} = 1;
1777: my $firstResource = $self->{HERE}->map_start();
1778: my $finishResource = $self->{HERE}->map_finish();
1779:
1780: $self->{RECURSIVE_ITERATOR} =
1781: Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource,
1782: $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
1783: $self->{CONDITION}, $self->{DIRECTION});
1784: }
1785:
1786: return $self->{HERE};
1787: }
1788:
1789: sub getStack {
1790: my $self=shift;
1791:
1792: my @stack;
1793:
1794: $self->populateStack(\@stack);
1795:
1796: return \@stack;
1797: }
1798:
1799: # Private method: Calls the iterators recursively to populate the stack.
1800: sub populateStack {
1801: my $self=shift;
1802: my $stack = shift;
1803:
1804: push @$stack, $self->{HERE} if ($self->{HERE});
1805:
1806: if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1807: $self->{RECURSIVE_ITERATOR}->populateStack($stack);
1808: }
1809: }
1810:
1811: 1;
1812:
1813: package Apache::lonnavmaps::resource;
1814:
1815: use Apache::lonnet;
1816:
1817: =pod
1818:
1819: =head1 Object: resource
1820:
1821: A resource object encapsulates a resource in a resource map, allowing easy manipulation of the resource, querying the properties of the resource (including user properties), and represents a reference that can be used as the canonical representation of the resource by lonnavmap clients like renderers.
1822:
1823: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
1824:
1825: You will probably never need to instantiate this object directly. Use Apache::lonnavmap::navmap, and use the "start" method to obtain the starting resource.
1826:
1827: =head2 Public Members
1828:
1829: resource objects have a hash called DATA ($resourceRef->{DATA}) that you can store whatever you want in. This allows you to easily do two-pass algorithms without worrying about managing your own resource->data hash.
1830:
1831: =head2 Methods
1832:
1833: =over 4
1834:
1835: =item * B<new>($navmapRef, $idString): The first arg is a reference to the parent navmap object. The second is the idString of the resource itself. Very rarely, if ever, called directly. Use the nav map->getByID() method.
1836:
1837: =back
1838:
1839: =cut
1840:
1841: sub new {
1842: # magic invocation to create a class instance
1843: my $proto = shift;
1844: my $class = ref($proto) || $proto;
1845: my $self = {};
1846:
1847: $self->{NAV_MAP} = shift;
1848: $self->{ID} = shift;
1849:
1850: # Store this new resource in the parent nav map's cache.
1851: $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
1852: $self->{RESOURCE_ERROR} = 0;
1853:
1854: # A hash that can be used by two-pass algorithms to store data
1855: # about this resource in. Not used by the resource object
1856: # directly.
1857: $self->{DATA} = {};
1858:
1859: bless($self);
1860:
1861: return $self;
1862: }
1863:
1864: # private function: simplify the NAV_HASH lookups we keep doing
1865: # pass the name, and to automatically append my ID, pass a true val on the
1866: # second param
1867: sub navHash {
1868: my $self = shift;
1869: my $param = shift;
1870: my $id = shift;
1871: return $self->{NAV_MAP}->{NAV_HASH}->{$param . ($id?$self->{ID}:"")};
1872: }
1873:
1874: =pod
1875:
1876: B<Metadata Retreival>
1877:
1878: These are methods that help you retrieve metadata about the resource:
1879:
1880: =over 4
1881:
1882: =item * B<ext>: Returns true if the resource is external.
1883:
1884: =item * B<goesto>: Returns the "goesto" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
1885:
1886: =item * B<kind>: Returns the kind of the resource from the compiled nav map.
1887:
1888: =item * B<randomout>: Returns true if this resource was chosen to NOT be shown to the user by the random map selection feature.
1889:
1890: =item * B<randompick>: Returns true for a map if the randompick feature is being used on the map. (?)
1891:
1892: =item * B<src>: Returns the source for the resource.
1893:
1894: =item * B<symb>: Returns the symb for the resource.
1895:
1896: =item * B<title>: Returns the title of the resource.
1897:
1898: =item * B<to>: Returns the "to" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
1899:
1900: =back
1901:
1902: =cut
1903:
1904: # These info functions can be used directly, as they don't return
1905: # resource information.
1906: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
1907: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
1908: sub from { my $self=shift; return $self->navHash("from_", 1); }
1909: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
1910: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
1911: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
1912: sub randompick {
1913: my $self = shift;
1914: return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
1915: '.0.parameter_randompick'};
1916: }
1917: sub src {
1918: my $self=shift;
1919: return $self->navHash("src_", 1);
1920: }
1921: sub symb {
1922: my $self=shift;
1923: (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
1924: my $symbSrc = &Apache::lonnet::declutter($self->src());
1925: return &Apache::lonnet::declutter(
1926: $self->navHash('map_id_'.$first))
1927: . '___' . $second . '___' . $symbSrc;
1928: }
1929: sub title { my $self=shift; return $self->navHash("title_", 1); }
1930: sub to { my $self=shift; return $self->navHash("to_", 1); }
1931:
1932: =pod
1933:
1934: B<Predicate Testing the Resource>
1935:
1936: These methods are shortcuts to deciding if a given resource has a given property.
1937:
1938: =over 4
1939:
1940: =item * B<is_map>: Returns true if the resource is a map type.
1941:
1942: =item * B<is_problem>: Returns true if the resource is a problem type, false otherwise. (Looks at the extension on the src field; might need more to work correctly.)
1943:
1944: =item * B<is_page>: Returns true if the resource is a page.
1945:
1946: =item * B<is_problem>: Returns true if the resource is a problem.
1947:
1948: =item * B<is_sequence>: Returns true if the resource sequence.
1949:
1950: =back
1951:
1952: =cut
1953:
1954:
1955: sub is_html {
1956: my $self=shift;
1957: my $src = $self->src();
1958: return ($src =~ /html$/);
1959: }
1960: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
1961: sub is_page {
1962: my $self=shift;
1963: my $src = $self->src();
1964: return ($src =~ /page$/);
1965: }
1966: sub is_problem {
1967: my $self=shift;
1968: my $src = $self->src();
1969: return ($src =~ /problem$/);
1970: }
1971: sub is_sequence {
1972: my $self=shift;
1973: my $src = $self->src();
1974: return ($src =~ /sequence$/);
1975: }
1976:
1977:
1978:
1979:
1980:
1981: # Move this into POD: In order to use these correctly, courseopt
1982: # and useropt need to be generated
1983: sub parmval {
1984: my $self = shift;
1985: my $what = shift;
1986: my $part = shift || "0";
1987: return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
1988: }
1989:
1990: =pod
1991:
1992: B<Map Methods>
1993:
1994: These methods are useful for getting information about the map properties of the resource, if the resource is a map (B<is_map>).
1995:
1996: =over 4
1997:
1998: =item * B<map_finish>: Returns a reference to a resource object corresponding to the finish resource of the map.
1999:
2000: =item * B<map_pc>: Returns the pc value of the map, which is the first number that appears in the resource ID of the resources in the map, and is the number that appears around the middle of the symbs of the resources in that map.
2001:
2002: =item * B<map_start>: Returns a reference to a resource object corresponding to the start resource of the map.
2003:
2004: =item * B<map_type>: Returns a string with the type of the map in it.
2005:
2006: =back
2007:
2008: =cut
2009:
2010: sub map_finish {
2011: my $self = shift;
2012: my $src = $self->src();
2013: my $res = $self->navHash("map_finish_$src", 0);
2014: $res = $self->{NAV_MAP}->getById($res);
2015: return $res;
2016: }
2017: sub map_pc {
2018: my $self = shift;
2019: my $src = $self->src();
2020: return $self->navHash("map_pc_$src", 0);
2021: }
2022: sub map_start {
2023: my $self = shift;
2024: my $src = $self->src();
2025: my $res = $self->navHash("map_start_$src", 0);
2026: $res = $self->{NAV_MAP}->getById($res);
2027: return $res;
2028: }
2029: sub map_type {
2030: my $self = shift;
2031: my $pc = $self->map_pc();
2032: return $self->navHash("map_type_$pc", 0);
2033: }
2034:
2035:
2036:
2037: #####
2038: # Property queries
2039: #####
2040:
2041: # These functions will be responsible for returning the CORRECT
2042: # VALUE for the parameter, no matter what. So while they may look
2043: # like direct calls to parmval, they can be more then that.
2044: # So, for instance, the duedate function should use the "duedatetype"
2045: # information, rather then the resource object user.
2046:
2047: =pod
2048:
2049: =head2 Resource Parameters
2050:
2051: In order to use the resource parameters correctly, the nav map must have been instantiated with genCourseAndUserOptions set to true, so the courseopt and useropt is read correctly. Then, you can call these functions to get the relevant parameters for the resource. Each function defaults to part "0", but can be directed to another part by passing the part as the parameter.
2052:
2053: These methods are responsible for getting the parameter correct, not merely reflecting the contents of the GDBM hashes. As we move towards dates relative to other dates, these methods should be updated to reflect that. (Then, anybody using these methods won't have to update their code.)
2054:
2055: =over 4
2056:
2057: =item * B<acc>: Get the Client IP/Name Access Control information.
2058:
2059: =item * B<answerdate>: Get the answer-reveal date for the problem.
2060:
2061: =item * B<duedate>: Get the due date for the problem.
2062:
2063: =item * B<tries>: Get the number of tries the student has used on the problem.
2064:
2065: =item * B<maxtries>: Get the number of max tries allowed.
2066:
2067: =item * B<opendate>: Get the open date for the problem.
2068:
2069: =item * B<sig>: Get the significant figures setting.
2070:
2071: =item * B<tol>: Get the tolerance for the problem.
2072:
2073: =item * B<tries>: Get the number of tries the user has already used on the problem.
2074:
2075: =item * B<type>: Get the question type for the problem.
2076:
2077: =item * B<weight>: Get the weight for the problem.
2078:
2079: =back
2080:
2081: =cut
2082:
2083: sub acc {
2084: (my $self, my $part) = @_;
2085: return $self->parmval("acc", $part);
2086: }
2087: sub answerdate {
2088: (my $self, my $part) = @_;
2089: # Handle intervals
2090: if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
2091: return $self->duedate($part) +
2092: $self->parmval("answerdate", $part);
2093: }
2094: return $self->parmval("answerdate", $part);
2095: }
2096: sub duedate {
2097: (my $self, my $part) = @_;
2098: return $self->parmval("duedate", $part);
2099: }
2100: sub maxtries {
2101: (my $self, my $part) = @_;
2102: return $self->parmval("maxtries", $part);
2103: }
2104: sub opendate {
2105: (my $self, my $part) = @_;
2106: if ($self->parmval("opendate.type", $part) eq 'date_interval') {
2107: return $self->duedate($part) -
2108: $self->parmval("opendate", $part);
2109: }
2110: return $self->parmval("opendate");
2111: }
2112: sub sig {
2113: (my $self, my $part) = @_;
2114: return $self->parmval("sig", $part);
2115: }
2116: sub tol {
2117: (my $self, my $part) = @_;
2118: return $self->parmval("tol", $part);
2119: }
2120: sub tries {
2121: my $self = shift;
2122: my $part = shift;
2123: $part = '0' if (!defined($part));
2124:
2125: # Make sure return hash is loaded, should error check
2126: $self->getReturnHash();
2127:
2128: my $tries = $self->{RETURN_HASH}->{'resource.'.$part.'.tries'};
2129: if (!defined($tries)) {return '0';}
2130: return $tries;
2131: }
2132: sub type {
2133: (my $self, my $part) = @_;
2134: return $self->parmval("type", $part);
2135: }
2136: sub weight {
2137: (my $self, my $part) = @_;
2138: return $self->parmval("weight", $part);
2139: }
2140:
2141: # Multiple things need this
2142: sub getReturnHash {
2143: my $self = shift;
2144:
2145: if (!defined($self->{RETURN_HASH})) {
2146: my %tmpHash = &Apache::lonnet::restore($self->symb());
2147: $self->{RETURN_HASH} = \%tmpHash;
2148: }
2149: }
2150:
2151: ######
2152: # Status queries
2153: ######
2154:
2155: # These methods query the status of problems.
2156:
2157: # If we need to count parts, this function determines the number of
2158: # parts from the metadata. When called, it returns a reference to a list
2159: # of strings corresponding to the parts. (Thus, using it in a scalar context
2160: # tells you how many parts you have in the problem:
2161: # $partcount = scalar($resource->countParts());
2162: # Don't use $self->{PARTS} directly because you don't know if it's been
2163: # computed yet.
2164:
2165: =pod
2166:
2167: =head2 Resource misc
2168:
2169: Misc. functions for the resource.
2170:
2171: =over 4
2172:
2173: =item * B<hasDiscussion>: Returns a false value if there has been discussion since the user last logged in, true if there has. Always returns false if the discussion data was not extracted when the nav map was constructed.
2174:
2175: =item * B<getFeedback>: Gets the feedback for the resource and returns the raw feedback string for the resource, or the null string if there is no feedback or the email data was not extracted when the nav map was constructed. Usually used like this:
2176:
2177: for (split(/\,/, $res->getFeedback())) {
2178: my $link = &Apache::lonnet::escape($_);
2179: ...
2180:
2181: and use the link as appropriate.
2182:
2183: =cut
2184:
2185: sub hasDiscussion {
2186: my $self = shift;
2187: return $self->{NAV_MAP}->hasDiscussion($self->symb());
2188: }
2189:
2190: sub getFeedback {
2191: my $self = shift;
2192: return $self->{NAV_MAP}->getFeedback($self->src());
2193: }
2194:
2195: =pod
2196:
2197: =item * B<parts>(): Returns a list reference containing sorted strings corresponding to each part of the problem. To count the number of parts, use the list in a scalar context, and subtract one if greater then two. (One part problems have a part 0. Multi-parts have a part 0, plus a part for each part. Filtering part 0 if you want it is up to you.)
2198:
2199: =item * B<countParts>(): Returns the number of parts of the problem a student can answer. Thus, for single part problems, returns 1. For multipart, it returns the number of parts in the problem, not including psuedo-part 0. Thus, B<parts> may return an array with fewer parts in it then countParts might lead you to believe.
2200:
2201: =back
2202:
2203: =cut
2204:
2205: sub parts {
2206: my $self = shift;
2207:
2208: if ($self->ext) { return ['0']; }
2209:
2210: $self->extractParts();
2211: return $self->{PARTS};
2212: }
2213:
2214: sub countParts {
2215: my $self = shift;
2216:
2217: my $parts = $self->parts();
2218:
2219: if ($self->{RESOURCE_ERROR}) {
2220: return 0;
2221: }
2222:
2223: if (scalar(@{$parts}) < 2) { return 1;}
2224:
2225: return scalar(@{$parts}) - 1;
2226: }
2227:
2228: # Private function: Extracts the parts information and saves it
2229: sub extractParts {
2230: my $self = shift;
2231:
2232: return if ($self->{PARTS});
2233: return if ($self->ext);
2234:
2235: $self->{PARTS} = [];
2236:
2237: # Retrieve part count, if this is a problem
2238: if ($self->is_problem()) {
2239: my $metadata = &Apache::lonnet::metadata($self->src(), 'allpossiblekeys');
2240: if (!$metadata) {
2241: $self->{RESOURCE_ERROR} = 1;
2242: $self->{PARTS} = [];
2243: return;
2244: }
2245:
2246: foreach (split(/\,/,$metadata)) {
2247: if ($_ =~ /^parameter\_(.*)\_opendate$/) {
2248: push @{$self->{PARTS}}, $1;
2249: }
2250: }
2251:
2252:
2253: # Is this possible to do in one line? - Jeremy
2254: my @sortedParts = sort @{$self->{PARTS}};
2255: $self->{PARTS} = \@sortedParts;
2256: }
2257:
2258: return;
2259: }
2260:
2261: =pod
2262:
2263: =head2 Resource Status
2264:
2265: Problem resources have status information, reflecting their various dates and completion statuses. You can obtain this information and import symbolic constants to represent the status.
2266:
2267: There are two aspects to the status: the date-related information and the completion information.
2268:
2269: Idiomatic usage of these two methods would probably look something like
2270:
2271: foreach ($resource->parts()) {
2272: my $dateStatus = $resource->getDateStatus($_);
2273: my $completionStatus = $resource->getCompletionStatus($_);
2274:
2275: or
2276:
2277: my $status = $resource->status($_);
2278:
2279: ... use it here ...
2280: }
2281:
2282: =over 4
2283:
2284: =item * B<getDateStatus>($part): ($part defaults to 0). A convenience function that returns a symbolic constant telling you about the date status of the part. The possible return values are:
2285:
2286: =back
2287:
2288: B<Date Codes>
2289:
2290: =over 4
2291:
2292: =item * B<OPEN_LATER>: The problem will be opened later.
2293:
2294: =item * B<OPEN>: Open and not yet due.
2295:
2296:
2297: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
2298:
2299: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
2300:
2301: =item * B<ANSWER_OPEN>: The answer date is here.
2302:
2303: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
2304:
2305: =back
2306:
2307: =cut
2308:
2309: # Apparently the compiler optimizes these into constants automatically
2310: sub OPEN_LATER { return 0; }
2311: sub OPEN { return 1; }
2312: sub PAST_DUE_NO_ANSWER { return 2; }
2313: sub PAST_DUE_ANSWER_LATER { return 3; }
2314: sub ANSWER_OPEN { return 4; }
2315: sub NOTHING_SET { return 5; }
2316: sub NETWORK_FAILURE { return 100; }
2317:
2318: # getDateStatus gets the date status for a given problem part.
2319: # Because answer date, due date, and open date are fully independent
2320: # (i.e., it is perfectly possible to *only* have an answer date),
2321: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
2322: # (past, future, none given). This function handles this with a decision
2323: # tree. Read the comments to follow the decision tree.
2324:
2325: sub getDateStatus {
2326: my $self = shift;
2327: my $part = shift;
2328: $part = "0" if (!defined($part));
2329:
2330: # Always return network failure if there was one.
2331: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2332:
2333: my $now = time();
2334:
2335: my $open = $self->opendate($part);
2336: my $due = $self->duedate($part);
2337: my $answer = $self->answerdate($part);
2338:
2339: if (!$open && !$due && !$answer) {
2340: # no data on the problem at all
2341: # should this be the same as "open later"? think multipart.
2342: return $self->NOTHING_SET;
2343: }
2344: if (!$open || $now < $open) {return $self->OPEN_LATER}
2345: if (!$due || $now < $due) {return $self->OPEN}
2346: if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
2347: if ($answer) { return $self->ANSWER_OPEN; }
2348: return PAST_DUE_NO_ANSWER;
2349: }
2350:
2351: =pod
2352:
2353: B<>
2354:
2355: =over 4
2356:
2357: =item * B<getCompletionStatus>($part): ($part defaults to 0.) A convenience function that returns a symbolic constant telling you about the completion status of the part, with the following possible results:
2358:
2359: =back
2360:
2361: B<Completion Codes>
2362:
2363: =over 4
2364:
2365: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
2366:
2367: =item * B<INCORRECT>: Attempted, but wrong by student.
2368:
2369: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
2370:
2371: =item * B<CORRECT>: Correct or correct by instructor.
2372:
2373: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
2374:
2375: =item * B<EXCUSED>: Excused. Not yet implemented.
2376:
2377: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
2378:
2379: =item * B<ATTEMPTED>: Attempted, and not yet graded.
2380:
2381: =back
2382:
2383: =cut
2384:
2385: sub NOT_ATTEMPTED { return 10; }
2386: sub INCORRECT { return 11; }
2387: sub INCORRECT_BY_OVERRIDE { return 12; }
2388: sub CORRECT { return 13; }
2389: sub CORRECT_BY_OVERRIDE { return 14; }
2390: sub EXCUSED { return 15; }
2391: sub ATTEMPTED { return 16; }
2392:
2393: sub getCompletionStatus {
2394: my $self = shift;
2395: my $part = shift;
2396: $part = "0" if (!defined($part));
2397: return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
2398:
2399: # Make sure return hash exists
2400: $self->getReturnHash();
2401:
2402: my $status = $self->{RETURN_HASH}->{'resource.'.$part.'.solved'};
2403:
2404: # Left as seperate if statements in case we ever do more with this
2405: if ($status eq 'correct_by_student') {return $self->CORRECT;}
2406: if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
2407: if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
2408: if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
2409: if ($status eq 'excused') {return $self->EXCUSED; }
2410: if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
2411: return $self->NOT_ATTEMPTED;
2412: }
2413:
2414: =pod
2415:
2416: B<Composite Status>
2417:
2418: Along with directly returning the date or completion status, the resource object includes a convenience function B<status>() that will combine the two status tidbits into one composite status that can represent the status of the resource as a whole. The precise logic is documented in the comments of the status method. The following results may be returned, all available as methods on the resource object ($res->NETWORK_FAILURE()):
2419:
2420: =over 4
2421:
2422: =item * B<NETWORK_FAILURE>: The network has failed and the information is not available.
2423:
2424: =item * B<NOTHING_SET>: No dates have been set for this problem (part) at all. (Because only certain parts of a multi-part problem may be assigned, this can not be collapsed into "open later", as we don't know a given part will EVER be opened. For single part, this is the same as "OPEN_LATER".)
2425:
2426: =item * B<CORRECT>: For any reason at all, the part is considered correct.
2427:
2428: =item * B<EXCUSED>: For any reason at all, the problem is excused.
2429:
2430: =item * B<PAST_DUE_NO_ANSWER>: The problem is past due, not considered correct, and no answer date is set.
2431:
2432: =item * B<PAST_DUE_ANSWER_LATER>: The problem is past due, not considered correct, and an answer date in the future is set.
2433:
2434: =item * B<ANSWER_OPEN>: The problem is past due, not correct, and the answer is now available.
2435:
2436: =item * B<OPEN_LATER>: The problem is not yet open.
2437:
2438: =item * B<TRIES_LEFT>: The problem is open, has been tried, is not correct, but there are tries left.
2439:
2440: =item * B<INCORRECT>: The problem is open, and all tries have been used without getting the correct answer.
2441:
2442: =item * B<OPEN>: The item is open and not yet tried.
2443:
2444: =item * B<ATTEMPTED>: The problem has been attempted.
2445:
2446: =back
2447:
2448: =cut
2449:
2450: sub TRIES_LEFT { return 10; }
2451:
2452: sub status {
2453: my $self = shift;
2454: my $part = shift;
2455: if (!defined($part)) { $part = "0"; }
2456: my $completionStatus = $self->getCompletionStatus($part);
2457: my $dateStatus = $self->getDateStatus($part);
2458:
2459: # What we have is a two-dimensional matrix with 4 entries on one
2460: # dimension and 5 entries on the other, which we want to colorize,
2461: # plus network failure and "no date data at all".
2462:
2463: if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
2464:
2465: # There are a few whole rows we can dispose of:
2466: if ($completionStatus == CORRECT ||
2467: $completionStatus == CORRECT_BY_OVERRIDE ) {
2468: return CORRECT;
2469: }
2470:
2471: if ($completionStatus == ATTEMPTED) {
2472: return ATTEMPTED;
2473: }
2474:
2475: # If it's EXCUSED, then return that no matter what
2476: if ($completionStatus == EXCUSED) {
2477: return EXCUSED;
2478: }
2479:
2480: if ($dateStatus == NOTHING_SET) {
2481: return NOTHING_SET;
2482: }
2483:
2484: # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
2485: # by 4 matrix (date statuses).
2486:
2487: if ($dateStatus == PAST_DUE_ANSWER_LATER ||
2488: $dateStatus == PAST_DUE_NO_ANSWER ) {
2489: return $dateStatus;
2490: }
2491:
2492: if ($dateStatus == ANSWER_OPEN) {
2493: return ANSWER_OPEN;
2494: }
2495:
2496: # Now: (incorrect, incorrect_override, not_attempted) x
2497: # (open_later), (open)
2498:
2499: if ($dateStatus == OPEN_LATER) {
2500: return OPEN_LATER;
2501: }
2502:
2503: # If it's WRONG...
2504: if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
2505: # and there are TRIES LEFT:
2506: if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
2507: return TRIES_LEFT;
2508: }
2509: return INCORRECT; # otherwise, return orange; student can't fix this
2510: }
2511:
2512: # Otherwise, it's untried and open
2513: return OPEN;
2514: }
2515:
2516: =pod
2517:
2518: =head2 Resource/Nav Map Navigation
2519:
2520: =over 4
2521:
2522: =item * B<getNext>($alreadySeenHashRef): Retreive an array of the possible next resources after this one. Always returns an array, even in the one- or zero-element case. The "alreadySeenHashRef" is an optional parameter that can be passed in to the method. If $$alreadySeenHashRef{$res->id()} is true in that hash, getNext will not return it in the list. In other words, you can use it to suppress resources you've already seen in the getNext method directly.
2523:
2524: =item * B<getPrevious>($alreadySeenHashRef): Retreive an array of the possible previous resources from this one. Always returns an array, even in the one- or zero-element case. $alreadySeenHashRef is the same as in getNext.
2525:
2526: =cut
2527:
2528: sub getNext {
2529: my $self = shift;
2530: my $alreadySeenHash = shift;
2531: my @branches;
2532: my $to = $self->to();
2533: foreach my $branch ( split(/,/, $to) ) {
2534: my $choice = $self->{NAV_MAP}->getById($branch);
2535: my $next = $choice->goesto();
2536: $next = $self->{NAV_MAP}->getById($next);
2537:
2538: # Don't remember it if we've already seen it or if
2539: # the student doesn't have browse priviledges
2540: my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
2541: if (!defined($alreadySeenHash) ||
2542: !defined($alreadySeenHash->{$next->{ID}}) ||
2543: ($browsePriv ne '2' && $browsePriv ne 'F')) {
2544: push @branches, $next;
2545: }
2546: }
2547: return \@branches;
2548: }
2549:
2550: sub getPrevious {
2551: my $self = shift;
2552: my $alreadySeenHash = shift;
2553: my @branches;
2554: my $from = $self->from();
2555: foreach my $branch ( split /,/, $from) {
2556: my $choice = $self->{NAV_MAP}->getById($branch);
2557: my $prev = $choice->comesfrom();
2558: $prev = $self->{NAV_MAP}->getById($prev);
2559:
2560: # Skip it if we've already seen it or the user doesn't have
2561: # browse privs
2562: my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
2563: if (!defined($alreadySeenHash) ||
2564: !defined($alreadySeenHash->{$prev->{ID}}) ||
2565: ($browsePriv ne '2' && $browsePriv ne 'F')) {
2566: push @branches, $prev;
2567: }
2568: }
2569: return \@branches;
2570: }
2571:
2572: =pod
2573:
2574: =back
2575:
2576: =cut
2577:
2578: 1;
2579:
2580: __END__
2581:
2582:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>