File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.118: download - view: text, annotated - select for diffs
Mon Dec 2 14:04:52 2002 UTC (21 years, 6 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Closes 979, assuming it works right. The "current document" marker and
the shifting the screen to keep what you just clicked on on the screen
have been fully dissociated, so that one resource can be labelled as
"here" (red angle brackets) while another is getting the anchor.

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

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