File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.132: download - view: text, annotated - select for diffs
Thu Jan 30 21:36:57 2003 UTC (21 years, 4 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Beginning the splitting of rendering and lonnavmap interface, so nav
maps can be easily rendered in a variety of manners and contexts.

This commit should have no visible effects on the nav maps screen itself.
If it does, that's a bug.

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>