File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.100: download - view: text, annotated - select for diffs
Fri Nov 8 19:10:58 2002 UTC (21 years, 7 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Flensed about 150 lines out of DFSiterator. Mostly removing the DFS
iterator's understanding of branches, which I recently learned was
flawed under some circumstances anyhow, so no great loss.

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

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