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