File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.239: download - view: text, annotated - select for diffs
Thu Oct 9 21:02:11 2003 UTC (20 years, 7 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
navmaps should now honor part order.

    1: # The LearningOnline Network with CAPA
    2: # Navigate Maps Handler
    3: #
    4: # $Id: lonnavmaps.pm,v 1.239 2003/10/09 21:02:11 bowersj2 Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # (Page Handler
   29: #
   30: # (TeX Content Handler
   31: #
   32: # 05/29/00,05/30 Gerd Kortemeyer)
   33: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
   34: # 10/02,10/10,10/14,10/16,10/18,10/19,10/31,11/6,11/14,11/16 Gerd Kortemeyer)
   35: #
   36: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
   37: # YEAR=2002
   38: # 1/1 Gerd Kortemeyer
   39: # Oct-Nov Jeremy Bowers
   40: # YEAR=2003
   41: # Jeremy Bowers ... lots of days
   42: 
   43: package Apache::lonnavmaps;
   44: 
   45: use strict;
   46: use Apache::Constants qw(:common :http);
   47: use Apache::loncommon();
   48: use Apache::lonmenu();
   49: use Apache::lonlocal;
   50: use POSIX qw (floor strftime);
   51: use Data::Dumper; # for debugging, not always used
   52: 
   53: # symbolic constants
   54: sub SYMB { return 1; }
   55: sub URL { return 2; }
   56: sub NOTHING { return 3; }
   57: 
   58: # Some data
   59: 
   60: my $resObj = "Apache::lonnavmaps::resource";
   61: 
   62: # Keep these mappings in sync with lonquickgrades, which uses the colors
   63: # instead of the icons.
   64: my %statusIconMap = 
   65:     (
   66:      $resObj->CLOSED       => '',
   67:      $resObj->OPEN         => 'navmap.open.gif',
   68:      $resObj->CORRECT      => 'navmap.correct.gif',
   69:      $resObj->INCORRECT    => 'navmap.wrong.gif',
   70:      $resObj->ATTEMPTED    => 'navmap.ellipsis.gif',
   71:      $resObj->ERROR        => ''
   72:      );
   73: 
   74: my %iconAltTags = 
   75:     ( 'navmap.correct.gif' => 'Correct',
   76:       'navmap.wrong.gif'   => 'Incorrect',
   77:       'navmap.open.gif'    => 'Open' );
   78: 
   79: # Defines a status->color mapping, null string means don't color
   80: my %colormap = 
   81:     ( $resObj->NETWORK_FAILURE        => '',
   82:       $resObj->CORRECT                => '',
   83:       $resObj->EXCUSED                => '#3333FF',
   84:       $resObj->PAST_DUE_ANSWER_LATER  => '',
   85:       $resObj->PAST_DUE_NO_ANSWER     => '',
   86:       $resObj->ANSWER_OPEN            => '#006600',
   87:       $resObj->OPEN_LATER             => '',
   88:       $resObj->TRIES_LEFT             => '',
   89:       $resObj->INCORRECT              => '',
   90:       $resObj->OPEN                   => '',
   91:       $resObj->NOTHING_SET            => '',
   92:       $resObj->ATTEMPTED              => '',
   93:       $resObj->ANSWER_SUBMITTED       => ''
   94:       );
   95: # And a special case in the nav map; what to do when the assignment
   96: # is not yet done and due in less then 24 hours
   97: my $hurryUpColor = "#FF0000";
   98: 
   99: sub handler {
  100:     my $r = shift;
  101:     real_handler($r);
  102: }
  103: 
  104: sub real_handler {
  105:     my $r = shift;
  106: 
  107:     # Handle header-only request
  108:     if ($r->header_only) {
  109:         if ($ENV{'browser.mathml'}) {
  110:             &Apache::loncommon::content_type($r,'text/xml');
  111:         } else {
  112:             &Apache::loncommon::content_type($r,'text/html');
  113:         }
  114:         $r->send_http_header;
  115:         return OK;
  116:     }
  117: 
  118:     # Send header, don't cache this page
  119:     if ($ENV{'browser.mathml'}) {
  120:         &Apache::loncommon::content_type($r,'text/xml');
  121:     } else {
  122:         &Apache::loncommon::content_type($r,'text/html');
  123:     }
  124:     &Apache::loncommon::no_cache($r);
  125:     $r->send_http_header;
  126: 
  127:     # Create the nav map
  128:     my $navmap = Apache::lonnavmaps::navmap->new();
  129: 
  130:     if (!defined($navmap)) {
  131:         my $requrl = $r->uri;
  132:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
  133:         return HTTP_NOT_ACCEPTABLE;
  134:     }
  135: 
  136:     $r->print("<html><head>\n");
  137:     $r->print("<title>".&mt('Navigate Course Contents')."</title>");
  138: # ------------------------------------------------------------ Get query string
  139:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['register']);
  140:     
  141: # ----------------------------------------------------- Force menu registration
  142:     my $addentries='';
  143:     if ($ENV{'form.register'}) {
  144:        $addentries=' onLoad="'.&Apache::lonmenu::loadevents().
  145: 	   '" onUnload="'.&Apache::lonmenu::unloadevents().'"';
  146:        $r->print(&Apache::lonmenu::registerurl(1));
  147:     }
  148: 
  149:     # Header
  150:     $r->print('</head>'.
  151:               &Apache::loncommon::bodytag('Navigate Course Contents','',
  152:                                     $addentries,'','',$ENV{'form.register'}));
  153:     $r->print('<script>window.focus();</script>');
  154: 
  155:     $r->rflush();
  156: 
  157:     # Check that it's defined
  158:     if (!($navmap->courseMapDefined())) {
  159:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
  160:                   '</body></html>');
  161:         return OK;
  162:     }
  163: 
  164:     # See if there's only one map in the top-level, if we don't
  165:     # already have a filter... if so, automatically display it
  166:     # (older code; should use retrieveResources)
  167:     if ($ENV{QUERY_STRING} !~ /filter/) {
  168:         my $iterator = $navmap->getIterator(undef, undef, undef, 0);
  169:         my $curRes;
  170:         my $sequenceCount = 0;
  171:         my $sequenceId;
  172:         while ($curRes = $iterator->next()) {
  173:             if (ref($curRes) && $curRes->is_sequence()) {
  174:                 $sequenceCount++;
  175:                 $sequenceId = $curRes->map_pc();
  176:             }
  177:         }
  178:         
  179:         if ($sequenceCount == 1) {
  180:             # The automatic iterator creation in the render call 
  181:             # will pick this up. We know the condition because
  182:             # the defined($ENV{'form.filter'}) also ensures this
  183:             # is a fresh call.
  184:             $ENV{'form.filter'} = "$sequenceId";
  185:         }
  186:     }
  187: 
  188:     my $jumpToFirstHomework = 0;
  189:     # Check to see if the student is jumping to next open, do-able problem
  190:     if ($ENV{QUERY_STRING} eq 'jumpToFirstHomework') {
  191:         $jumpToFirstHomework = 1;
  192:         # Find the next homework problem that they can do.
  193:         my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  194:         my $curRes;
  195:         my $foundDoableProblem = 0;
  196:         my $problemRes;
  197:         
  198:         while (($curRes = $iterator->next()) && !$foundDoableProblem) {
  199:             if (ref($curRes) && $curRes->is_problem()) {
  200:                 my $status = $curRes->status();
  201:                 if ($curRes->completable()) {
  202:                     $problemRes = $curRes;
  203:                     $foundDoableProblem = 1;
  204: 
  205:                     # Pop open all previous maps
  206:                     my $stack = $iterator->getStack();
  207:                     pop @$stack; # last resource in the stack is the problem
  208:                                  # itself, which we don't need in the map stack
  209:                     my @mapPcs = map {$_->map_pc()} @$stack;
  210:                     $ENV{'form.filter'} = join(',', @mapPcs);
  211: 
  212:                     # Mark as both "here" and "jump"
  213:                     $ENV{'form.postsymb'} = $curRes->symb();
  214:                 }
  215:             }
  216:         }
  217: 
  218:         # If we found no problems, print a note to that effect.
  219:         if (!$foundDoableProblem) {
  220:             $r->print("<font size='+2'>All homework assignments have been completed.</font><br /><br />");
  221:         }
  222:     } else {
  223:         $r->print("<a href='navmaps?jumpToFirstHomework'>" .
  224:        &mt("Go To My First Homework Problem")."</a>&nbsp;&nbsp;&nbsp;&nbsp;");
  225:     }
  226: 
  227:     my $suppressEmptySequences = 0;
  228:     my $filterFunc = undef;
  229:     my $resource_no_folder_link = 0;
  230: 
  231:     # Display only due homework.
  232:     my $showOnlyHomework = 0;
  233:     if ($ENV{QUERY_STRING} eq 'showOnlyHomework') {
  234:         $showOnlyHomework = 1;
  235:         $suppressEmptySequences = 1;
  236:         $filterFunc = sub { my $res = shift; 
  237:                             return $res->completable() || $res->is_map();
  238:                         };
  239:         $r->print("<p><font size='+2'>".&mt("Uncompleted Homework")."</font></p>");
  240:         $ENV{'form.filter'} = '';
  241:         $ENV{'form.condition'} = 1;
  242: 	$resource_no_folder_link = 1;
  243:     } else {
  244:         $r->print("<a href='navmaps?showOnlyHomework'>" .
  245:        &mt("Show Only Uncompleted Homework")."</a>&nbsp;&nbsp;&nbsp;&nbsp;");
  246:     }
  247: 
  248:     # renderer call
  249:     my $renderArgs = { 'cols' => [0,1,2,3],
  250:                        'url' => '/adm/navmaps',
  251:                        'navmap' => $navmap,
  252:                        'suppressNavmap' => 1,
  253:                        'suppressEmptySequences' => $suppressEmptySequences,
  254:                        'filterFunc' => $filterFunc,
  255: 		       'resource_no_folder_link' => $resource_no_folder_link,
  256:                        'r' => $r};
  257:     my $render = render($renderArgs);
  258:     $navmap->untieHashes();
  259: 
  260:     # If no resources were printed, print a reassuring message so the
  261:     # user knows there was no error.
  262:     if ($renderArgs->{'counter'} == 0) {
  263:         if ($showOnlyHomework) {
  264:             $r->print("<p><font size='+1'>".&mt("All homework is currently completed").".</font></p>");
  265:         } else { # both jumpToFirstHomework and normal use the same: course must be empty
  266:             $r->print("<p><font size='+1'>This course is empty.</font></p>");
  267:         }
  268:     }
  269: 
  270:     $r->print("</body></html>");
  271:     $r->rflush();
  272: 
  273:     return OK;
  274: }
  275: 
  276: # Convenience functions: Returns a string that adds or subtracts
  277: # the second argument from the first hash, appropriate for the 
  278: # query string that determines which folders to recurse on
  279: sub addToFilter {
  280:     my $hashIn = shift;
  281:     my $addition = shift;
  282:     my %hash = %$hashIn;
  283:     $hash{$addition} = 1;
  284: 
  285:     return join (",", keys(%hash));
  286: }
  287: 
  288: sub removeFromFilter {
  289:     my $hashIn = shift;
  290:     my $subtraction = shift;
  291:     my %hash = %$hashIn;
  292: 
  293:     delete $hash{$subtraction};
  294:     return join(",", keys(%hash));
  295: }
  296: 
  297: # Convenience function: Given a stack returned from getStack on the iterator,
  298: # return the correct src() value.
  299: # Later, this should add an anchor when we start putting anchors in pages.
  300: sub getLinkForResource {
  301:     my $stack = shift;
  302:     my $res;
  303: 
  304:     # Check to see if there are any pages in the stack
  305:     foreach $res (@$stack) {
  306:         if (defined($res) && $res->is_page()) {
  307:             return $res->src();
  308:         }
  309:     }
  310: 
  311:     # Failing that, return the src of the last resource that is defined
  312:     # (when we first recurse on a map, it puts an undefined resource
  313:     # on the bottom because $self->{HERE} isn't defined yet, and we
  314:     # want the src for the map anyhow)
  315:     foreach (@$stack) {
  316:         if (defined($_)) { $res = $_; }
  317:     }
  318: 
  319:     return $res->src();
  320: }
  321: 
  322: # Convenience function: This seperates the logic of how to create
  323: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
  324: # etc.) into a seperate function. It takes a resource object as the
  325: # first parameter, and the part number of the resource as the second.
  326: # It's basically a big switch statement on the status of the resource.
  327: 
  328: sub getDescription {
  329:     my $res = shift;
  330:     my $part = shift;
  331:     my $status = $res->status($part);
  332: 
  333:     if ($status == $res->NETWORK_FAILURE) { 
  334:         return &mt("Having technical difficulties; please check status later"); 
  335:     }
  336:     if ($status == $res->NOTHING_SET) {
  337:         return &mt("Not currently assigned.");
  338:     }
  339:     if ($status == $res->OPEN_LATER) {
  340:         return "Open " . timeToHumanString($res->opendate($part));
  341:     }
  342:     if ($status == $res->OPEN) {
  343:         if ($res->duedate($part)) {
  344:             return &mt("Due")."  " .timeToHumanString($res->duedate($part));
  345:         } else {
  346:             return &mt("Open, no due date");
  347:         }
  348:     }
  349:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
  350:         return &mt("Answer open")." " . timeToHumanString($res->answerdate($part));
  351:     }
  352:     if ($status == $res->PAST_DUE_NO_ANSWER) {
  353:         return &mt("Was due")." " . timeToHumanString($res->duedate($part));
  354:     }
  355:     if ($status == $res->ANSWER_OPEN) {
  356:         return &mt("Answer available");
  357:     }
  358:     if ($status == $res->EXCUSED) {
  359:         return &mt("Excused by instructor");
  360:     }
  361:     if ($status == $res->ATTEMPTED) {
  362:         return &mt("Answer submitted, not yet graded");
  363:     }
  364:     if ($status == $res->TRIES_LEFT) {
  365:         my $tries = $res->tries($part);
  366:         my $maxtries = $res->maxtries($part);
  367:         my $triesString = "";
  368:         if ($tries && $maxtries) {
  369:             $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
  370:             if ($maxtries > 1 && $maxtries - $tries == 1) {
  371:                 $triesString = "<b>$triesString</b>";
  372:             }
  373:         }
  374:         if ($res->duedate()) {
  375:             return &mt("Due")." " . timeToHumanString($res->duedate($part)) .
  376:                 " $triesString";
  377:         } else {
  378:             return &mt("No due date")." $triesString";
  379:         }
  380:     }
  381:     if ($status == $res->ANSWER_SUBMITTED) {
  382:         return &mt('Answer submitted');
  383:     }
  384: }
  385: 
  386: # Convenience function, so others can use it: Is the problem due in less then
  387: # 24 hours, and still can be done?
  388: 
  389: sub dueInLessThen24Hours {
  390:     my $res = shift;
  391:     my $part = shift;
  392:     my $status = $res->status($part);
  393: 
  394:     return ($status == $res->OPEN() ||
  395:             $status == $res->TRIES_LEFT()) &&
  396:            $res->duedate() && $res->duedate() < time()+(24*60*60) &&
  397:            $res->duedate() > time();
  398: }
  399: 
  400: # Convenience function, so others can use it: Is there only one try remaining for the
  401: # part, with more then one try to begin with, not due yet and still can be done?
  402: sub lastTry {
  403:     my $res = shift;
  404:     my $part = shift;
  405: 
  406:     my $tries = $res->tries($part);
  407:     my $maxtries = $res->maxtries($part);
  408:     return $tries && $maxtries && $maxtries > 1 &&
  409:         $maxtries - $tries == 1 && $res->duedate() &&
  410:         $res->duedate() > time();
  411: }
  412: 
  413: # This puts a human-readable name on the ENV variable.
  414: 
  415: sub advancedUser {
  416:     return $ENV{'request.role.adv'};
  417: }
  418: 
  419: 
  420: # timeToHumanString takes a time number and converts it to a
  421: # human-readable representation, meant to be used in the following
  422: # manner:
  423: # print "Due $timestring"
  424: # print "Open $timestring"
  425: # print "Answer available $timestring"
  426: # Very, very, very, VERY English-only... goodness help a localizer on
  427: # this func...
  428: sub timeToHumanString {
  429:     my ($time) = @_;
  430:     # zero, '0' and blank are bad times
  431:     if (!$time) {
  432:         return &mt('never');
  433:     }
  434:     unless (&Apache::lonlocal::current_language()=~/^en/) {
  435: 	return &Apache::lonlocal::locallocaltime($time);
  436:     } 
  437:     my $now = time();
  438: 
  439:     my @time = localtime($time);
  440:     my @now = localtime($now);
  441: 
  442:     # Positive = future
  443:     my $delta = $time - $now;
  444: 
  445:     my $minute = 60;
  446:     my $hour = 60 * $minute;
  447:     my $day = 24 * $hour;
  448:     my $week = 7 * $day;
  449:     my $inPast = 0;
  450: 
  451:     # Logic in comments:
  452:     # Is it now? (extremely unlikely)
  453:     if ( $delta == 0 ) {
  454:         return "this instant";
  455:     }
  456: 
  457:     if ($delta < 0) {
  458:         $inPast = 1;
  459:         $delta = -$delta;
  460:     }
  461: 
  462:     if ( $delta > 0 ) {
  463: 
  464:         my $tense = $inPast ? " ago" : "";
  465:         my $prefix = $inPast ? "" : "in ";
  466:         
  467:         # Less then a minute
  468:         if ( $delta < $minute ) {
  469:             if ($delta == 1) { return "${prefix}1 second$tense"; }
  470:             return "$prefix$delta seconds$tense";
  471:         }
  472: 
  473:         # Less then an hour
  474:         if ( $delta < $hour ) {
  475:             # If so, use minutes
  476:             my $minutes = floor($delta / 60);
  477:             if ($minutes == 1) { return "${prefix}1 minute$tense"; }
  478:             return "$prefix$minutes minutes$tense";
  479:         }
  480:         
  481:         # Is it less then 24 hours away? If so,
  482:         # display hours + minutes
  483:         if ( $delta < $hour * 24) {
  484:             my $hours = floor($delta / $hour);
  485:             my $minutes = floor(($delta % $hour) / $minute);
  486:             my $hourString = "$hours hours";
  487:             my $minuteString = ", $minutes minutes";
  488:             if ($hours == 1) {
  489:                 $hourString = "1 hour";
  490:             }
  491:             if ($minutes == 1) {
  492:                 $minuteString = ", 1 minute";
  493:             }
  494:             if ($minutes == 0) {
  495:                 $minuteString = "";
  496:             }
  497:             return "$prefix$hourString$minuteString$tense";
  498:         }
  499: 
  500:         # Less then 5 days away, display day of the week and
  501:         # HH:MM
  502:         if ( $delta < $day * 5 ) {
  503:             my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
  504:             $timeStr =~ s/12:00 am/00:00/;
  505:             $timeStr =~ s/12:00 pm/noon/;
  506:             return ($inPast ? "last " : "next ") .
  507:                 $timeStr;
  508:         }
  509:         
  510:         # Is it this year?
  511:         if ( $time[5] == $now[5]) {
  512:             # Return on Month Day, HH:MM meridian
  513:             my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
  514:             $timeStr =~ s/12:00 am/00:00/;
  515:             $timeStr =~ s/12:00 pm/noon/;
  516:             return $timeStr;
  517:         }
  518: 
  519:         # Not this year, so show the year
  520:         my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
  521:         $timeStr =~ s/12:00 am/00:00/;
  522:         $timeStr =~ s/12:00 pm/noon/;
  523:         return $timeStr;
  524:     }
  525: }
  526: 
  527: 
  528: =pod
  529: 
  530: =head1 NAME
  531: 
  532: Apache::lonnavmap - Subroutines to handle and render the navigation
  533:     maps
  534: 
  535: =head1 SYNOPSIS
  536: 
  537: The main handler generates the navigational listing for the course,
  538: the other objects export this information in a usable fashion for
  539: other modules.
  540: 
  541: =head1 OVERVIEW
  542: 
  543: X<lonnavmaps, overview> When a user enters a course, LON-CAPA examines the
  544: course structure and caches it in what is often referred to as the
  545: "big hash" X<big hash>. You can see it if you are logged into
  546: LON-CAPA, in a course, by going to /adm/test. (You may need to
  547: tweak the /home/httpd/lonTabs/htpasswd file to view it.) The
  548: content of the hash will be under the heading "Big Hash".
  549: 
  550: Big Hash contains, among other things, how resources are related
  551: to each other (next/previous), what resources are maps, which 
  552: resources are being chosen to not show to the student (for random
  553: selection), and a lot of other things that can take a lot of time
  554: to compute due to the amount of data that needs to be collected and
  555: processed.
  556: 
  557: Apache::lonnavmaps provides an object model for manipulating this
  558: information in a higher-level fashion then directly manipulating 
  559: the hash. It also provides access to several auxilary functions 
  560: that aren't necessarily stored in the Big Hash, but are a per-
  561: resource sort of value, like whether there is any feedback on 
  562: a given resource.
  563: 
  564: Apache::lonnavmaps also abstracts away branching, and someday, 
  565: conditions, for the times where you don't really care about those
  566: things.
  567: 
  568: Apache::lonnavmaps also provides fairly powerful routines for
  569: rendering navmaps, and last but not least, provides the navmaps
  570: view for when the user clicks the NAV button.
  571: 
  572: B<Note>: Apache::lonnavmaps I<only> works for the "currently
  573: logged in user"; if you want things like "due dates for another
  574: student" lonnavmaps can not directly retrieve information like
  575: that. You need the EXT function. This module can still help,
  576: because many things, such as the course structure, are constant
  577: between users, and Apache::lonnavmaps can help by providing
  578: symbs for the EXT call.
  579: 
  580: The rest of this file will cover the provided rendering routines, 
  581: which can often be used without fiddling with the navmap object at
  582: all, then documents the Apache::lonnavmaps::navmap object, which
  583: is the key to accessing the Big Hash information, covers the use
  584: of the Iterator (which provides the logic for traversing the 
  585: somewhat-complicated Big Hash data structure), documents the
  586: Apache::lonnavmaps::Resource objects that are returned by 
  587: 
  588: =head1 Subroutine: render
  589: 
  590: The navmap renderer package provides a sophisticated rendering of the
  591: standard navigation maps interface into HTML. The provided nav map
  592: handler is actually just a glorified call to this.
  593: 
  594: Because of the large number of parameters this function accepts,
  595: instead of passing it arguments as is normal, pass it in an anonymous
  596: hash with the desired options.
  597: 
  598: The package provides a function called 'render', called as
  599: Apache::lonnavmaps::render({}).
  600: 
  601: =head2 Overview of Columns
  602: 
  603: The renderer will build an HTML table for the navmap and return
  604: it. The table is consists of several columns, and a row for each
  605: resource (or possibly each part). You tell the renderer how many
  606: columns to create and what to place in each column, optionally using
  607: one or more of the prepared columns, and the renderer will assemble
  608: the table.
  609: 
  610: Any additional generally useful column types should be placed in the
  611: renderer code here, so anybody can use it anywhere else. Any code
  612: specific to the current application (such as the addition of <input>
  613: elements in a column) should be placed in the code of the thing using
  614: the renderer.
  615: 
  616: At the core of the renderer is the array reference COLS (see Example
  617: section below for how to pass this correctly). The COLS array will
  618: consist of entries of one of two types of things: Either an integer
  619: representing one of the pre-packaged column types, or a sub reference
  620: that takes a resource reference, a part number, and a reference to the
  621: argument hash passed to the renderer, and returns a string that will
  622: be inserted into the HTML representation as it.
  623: 
  624: All other parameters are ways of either changing how the columns
  625: are printing, or which rows are shown.
  626: 
  627: The pre-packaged column names are refered to by constants in the
  628: Apache::lonnavmaps namespace. The following currently exist:
  629: 
  630: =over 4
  631: 
  632: =item * B<Apache::lonnavmaps::resource>:
  633: 
  634: The general info about the resource: Link, icon for the type, etc. The
  635: first column in the standard nav map display. This column provides the
  636: indentation effect seen in the B<NAV> screen. This column also accepts
  637: the following parameters in the renderer hash:
  638: 
  639: =over 4
  640: 
  641: =item * B<resource_nolink>: default false
  642: 
  643: If true, the resource will not be linked. By default, all non-folder
  644: resources are linked.
  645: 
  646: =item * B<resource_part_count>: default true
  647: 
  648: If true, the resource will show a part count B<if> the full
  649: part list is not displayed. (See "condense_parts" later.) If false,
  650: the resource will never show a part count.
  651: 
  652: =item * B<resource_no_folder_link>:
  653: 
  654: If true, the resource's folder will not be clickable to open or close
  655: it. Default is false. True implies printCloseAll is false, since you
  656: can't close or open folders when this is on anyhow.
  657: 
  658: =back
  659: 
  660: =item * B<Apache::lonnavmaps::communication_status>:
  661: 
  662: Whether there is discussion on the resource, email for the user, or
  663: (lumped in here) perl errors in the execution of the problem. This is
  664: the second column in the main nav map.
  665: 
  666: =item * B<Apache::lonnavmaps::quick_status>:
  667: 
  668: An icon for the status of a problem, with five possible states:
  669: Correct, incorrect, open, awaiting grading (for a problem where the
  670: computer's grade is suppressed, or the computer can't grade, like
  671: essay problem), or none (not open yet, not a problem). The
  672: third column of the standard navmap.
  673: 
  674: =item * B<Apache::lonnavmaps::long_status>:
  675: 
  676: A text readout of the details of the current status of the problem,
  677: such as "Due in 22 hours". The fourth column of the standard navmap.
  678: 
  679: =item * B<Apache::lonnavmaps::part_status_summary>:
  680: 
  681: A text readout summarizing the status of the problem. If it is a
  682: single part problem, will display "Correct", "Incorrect", 
  683: "Not yet open", "Open", "Attempted", or "Error". If there are
  684: multiple parts, this will output a string that in HTML will show a
  685: status of how many parts are in each status, in color coding, trying
  686: to match the colors of the icons within reason.
  687: 
  688: Note this only makes sense if you are I<not> showing parts. If 
  689: C<showParts> is true (see below), this column will not output
  690: anything. 
  691: 
  692: =back
  693: 
  694: If you add any others please be sure to document them here.
  695: 
  696: An example of a column renderer that will show the ID number of a
  697: resource, along with the part name if any:
  698: 
  699:  sub { 
  700:   my ($resource, $part, $params) = @_;   
  701:   if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
  702:   return '<td>' . $resource->{ID} . '</td>';
  703:  }
  704: 
  705: Note these functions are responsible for the TD tags, which allow them
  706: to override vertical and horizontal alignment, etc.
  707: 
  708: =head2 Parameters
  709: 
  710: Minimally, you should be
  711: able to get away with just using 'cols' (to specify the columns
  712: shown), 'url' (necessary for the folders to link to the current screen
  713: correctly), and possibly 'queryString' if your app calls for it. In
  714: that case, maintaining the state of the folders will be done
  715: automatically.
  716: 
  717: =over 4
  718: 
  719: =item * B<iterator>: default: constructs one from %ENV
  720: 
  721: A reference to a fresh ::iterator to use from the navmaps. The
  722: rendering will reflect the options passed to the iterator, so you can
  723: use that to just render a certain part of the course, if you like. If
  724: one is not passed, the renderer will attempt to construct one from
  725: ENV{'form.filter'} and ENV{'form.condition'} information, plus the
  726: 'iterator_map' parameter if any.
  727: 
  728: =item * B<iterator_map>: default: not used
  729: 
  730: If you are letting the renderer do the iterator handling, you can
  731: instruct the renderer to render only a particular map by passing it
  732: the source of the map you want to process, like
  733: '/res/103/jerf/navmap.course.sequence'.
  734: 
  735: =item * B<navmap>: default: constructs one from %ENV
  736: 
  737: A reference to a navmap, used only if an iterator is not passed in. If
  738: this is necessary to make an iterator but it is not passed in, a new
  739: one will be constructed based on ENV info. This is useful to do basic
  740: error checking before passing it off to render.
  741: 
  742: =item * B<r>: default: must be passed in
  743: 
  744: The standard Apache response object. This must be passed to the
  745: renderer or the course hash will be locked.
  746: 
  747: =item * B<cols>: default: empty (useless)
  748: 
  749: An array reference
  750: 
  751: =item * B<showParts>:default true
  752: 
  753: A flag. If true, a line for the resource itself, and a line
  754: for each part will be displayed. If not, only one line for each
  755: resource will be displayed.
  756: 
  757: =item * B<condenseParts>: default true
  758: 
  759: A flag. If true, if all parts of the problem have the same
  760: status and that status is Nothing Set, Correct, or Network Failure,
  761: then only one line will be displayed for that resource anyhow. If no,
  762: all parts will always be displayed. If showParts is 0, this is
  763: ignored.
  764: 
  765: =item * B<jumpCount>: default: determined from %ENV
  766: 
  767: A string identifying the URL to place the anchor 'curloc' at.
  768: It is the responsibility of the renderer user to
  769: ensure that the #curloc is in the URL. By default, determined through
  770: the use of the ENV{} 'jump' information, and should normally "just
  771: work" correctly.
  772: 
  773: =item * B<here>: default: empty string
  774: 
  775: A Symb identifying where to place the 'here' marker. The empty
  776: string means no marker.
  777: 
  778: =item * B<indentString>: default: 25 pixel whitespace image
  779: 
  780: A string identifying the indentation string to use. 
  781: 
  782: =item * B<queryString>: default: empty
  783: 
  784: A string which will be prepended to the query string used when the
  785: folders are opened or closed. You can use this to pass
  786: application-specific values.
  787: 
  788: =item * B<url>: default: none
  789: 
  790: The url the folders will link to, which should be the current
  791: page. Required if the resource info column is shown, and you 
  792: are allowing the user to open and close folders.
  793: 
  794: =item * B<currentJumpIndex>: default: no jumping
  795: 
  796: Describes the currently-open row number to cause the browser to jump
  797: to, because the user just opened that folder. By default, pulled from
  798: the Jump information in the ENV{'form.*'}.
  799: 
  800: =item * B<printKey>: default: false
  801: 
  802: If true, print the key that appears on the top of the standard
  803: navmaps.
  804: 
  805: =item * B<printCloseAll>: default: true
  806: 
  807: If true, print the "Close all folders" or "open all folders"
  808: links.
  809: 
  810: =item * B<filterFunc>: default: sub {return 1;} (accept everything)
  811: 
  812: A function that takes the resource object as its only parameter and
  813: returns a true or false value. If true, the resource is displayed. If
  814: false, it is simply skipped in the display.
  815: 
  816: =item * B<suppressEmptySequences>: default: false
  817: 
  818: If you're using a filter function, and displaying sequences to orient
  819: the user, then frequently some sequences will be empty. Setting this to
  820: true will cause those sequences not to display, so as not to confuse the
  821: user into thinking that if the sequence is there there should be things
  822: under it; for example, see the "Show Uncompleted Homework" view on the
  823: B<NAV> screen.
  824: 
  825: =item * B<suppressNavmaps>: default: false
  826: 
  827: If true, will not display Navigate Content resources. 
  828: 
  829: =back
  830: 
  831: =head2 Additional Info
  832: 
  833: In addition to the parameters you can pass to the renderer, which will
  834: be passed through unchange to the column renderers, the renderer will
  835: generate the following information which your renderer may find
  836: useful:
  837: 
  838: =over 4
  839: 
  840: =item * B<counter>: 
  841: 
  842: Contains the number of rows printed. Useful after calling the render 
  843: function, as you can detect whether anything was printed at all.
  844: 
  845: =item * B<isNewBranch>:
  846: 
  847: Useful for renderers: If this resource is currently the first resource
  848: of a new branch, this will be true. The Resource column (leftmost in the
  849: navmaps screen) uses this to display the "new branch" icon 
  850: 
  851: =back
  852: 
  853: =cut
  854: 
  855: sub resource { return 0; }
  856: sub communication_status { return 1; }
  857: sub quick_status { return 2; }
  858: sub long_status { return 3; }
  859: sub part_status_summary { return 4; }
  860: 
  861: sub render_resource {
  862:     my ($resource, $part, $params) = @_;
  863: 
  864:     my $nonLinkedText = ''; # stuff after resource title not in link
  865: 
  866:     my $link = $params->{"resourceLink"};
  867:     my $src = $resource->src();
  868:     my $it = $params->{"iterator"};
  869:     my $filter = $it->{FILTER};
  870: 
  871:     my $title = $resource->compTitle();
  872:     if ($src =~ /^\/uploaded\//) {
  873:         $nonLinkedText=$title;
  874:         $title = '';
  875:     }
  876:     my $partLabel = "";
  877:     my $newBranchText = "";
  878:     
  879:     # If this is a new branch, label it so
  880:     if ($params->{'isNewBranch'}) {
  881:         $newBranchText = "<img src='/adm/lonIcons/branch.gif' border='0' />";
  882:     }
  883: 
  884:     # links to open and close the folder
  885:     my $linkopen = "<a href='$link'>";
  886:     my $linkclose = "</a>";
  887: 
  888:     # Default icon: unknown page
  889:     my $icon = "<img src='/adm/lonIcons/unknown.gif' alt='' border='0' />";
  890:     
  891:     if ($resource->is_problem()) {
  892:         if ($part eq '0' || $params->{'condensed'}) {
  893:             $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border="0" />';
  894:         } else {
  895:             $icon = $params->{'indentString'};
  896:         }
  897:     } else {
  898: 	my $curfext= (split (/\./,$resource->src))[-1];
  899: 	my $embstyle = &Apache::loncommon::fileembstyle($curfext);
  900: 	# The unless conditional that follows is a bit of overkill
  901: 	if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
  902: 	    $icon = "<img src='/adm/lonIcons/$curfext.gif' alt='' border='0' />";
  903: 	}
  904:     }
  905: 
  906:     # Display the correct map icon to open or shut map
  907:     if ($resource->is_map()) {
  908:         my $mapId = $resource->map_pc();
  909:         my $nowOpen = !defined($filter->{$mapId});
  910:         if ($it->{CONDITION}) {
  911:             $nowOpen = !$nowOpen;
  912:         }
  913: 
  914: 	my $folderType = $resource->is_sequence() ? 'folder' : 'page';
  915: 
  916:         if (!$params->{'resource_no_folder_link'}) {
  917:             $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
  918:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
  919: 
  920:             $linkopen = "<a href='" . $params->{'url'} . '?' . 
  921:                 $params->{'queryString'} . '&filter=';
  922:             $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
  923:                 addToFilter($filter, $mapId) :
  924:                 removeFromFilter($filter, $mapId);
  925:             $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
  926:                 . $params->{'hereType'} . '&here=' .
  927:                 &Apache::lonnet::escape($params->{'here'}) . 
  928:                 '&jump=' .
  929:                 &Apache::lonnet::escape($resource->symb()) . 
  930:                 "&folderManip=1'>";
  931:         } else {
  932:             # Don't allow users to manipulate folder
  933:             $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') .
  934:                 '.nomanip.gif';
  935:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
  936: 
  937:             $linkopen = "";
  938:             $linkclose = "";
  939:         }
  940:     }
  941: 
  942:     if ($resource->randomout()) {
  943:         $nonLinkedText .= ' <i>(hidden)</i> ';
  944:     }
  945:     
  946:     # We're done preparing and finally ready to start the rendering
  947:     my $result = "<td align='left' valign='center'>";
  948: 
  949:     my $indentLevel = $params->{'indentLevel'};
  950:     if ($newBranchText) { $indentLevel--; }
  951: 
  952:     # print indentation
  953:     for (my $i = 0; $i < $indentLevel; $i++) {
  954:         $result .= $params->{'indentString'};
  955:     }
  956: 
  957:     # Decide what to display
  958:     $result .= "$newBranchText$linkopen$icon$linkclose";
  959:     
  960:     my $curMarkerBegin = '';
  961:     my $curMarkerEnd = '';
  962: 
  963:     # Is this the current resource?
  964:     if (!$params->{'displayedHereMarker'} && 
  965:         $resource->symb() eq $params->{'here'} ) {
  966:         $curMarkerBegin = '<font color="red" size="+2">&gt; </font>';
  967:         $curMarkerEnd = '<font color="red" size="+2">&lt;</font>';
  968:         $params->{'displayedHereMarker'} = 1;
  969:     }
  970: 
  971:     if ($resource->is_problem() && $part ne '0' && 
  972:         !$params->{'condensed'}) {
  973:         $partLabel = " (Part $part)";
  974:         $title = "";
  975:     }
  976: 
  977:     if ($params->{'condensed'} && $resource->countParts() > 1) {
  978:         $nonLinkedText .= ' (' . $resource->countParts() . ' parts)';
  979:     }
  980: 
  981:     if (!$params->{'resource_nolink'} && $src !~ /^\/uploaded\// &&
  982: 	!$resource->is_sequence()) {
  983:         $result .= "  $curMarkerBegin<a href='$link'>$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
  984:     } else {
  985:         $result .= "  $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
  986:     }
  987: 
  988:     return $result;
  989: }
  990: 
  991: sub render_communication_status {
  992:     my ($resource, $part, $params) = @_;
  993:     my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
  994: 
  995:     my $link = $params->{"resourceLink"};
  996:     my $linkopen = "<a href='$link'>";
  997:     my $linkclose = "</a>";
  998: 
  999:     if ($resource->hasDiscussion()) {
 1000:         $discussionHTML = $linkopen .
 1001:             '<img border="0" src="/adm/lonMisc/chat.gif" />' .
 1002:             $linkclose;
 1003:     }
 1004:     
 1005:     if ($resource->getFeedback()) {
 1006:         my $feedback = $resource->getFeedback();
 1007:         foreach (split(/\,/, $feedback)) {
 1008:             if ($_) {
 1009:                 $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
 1010:                     . &Apache::lonnet::escape($_) . '">'
 1011:                     . '<img src="/adm/lonMisc/feedback.gif" '
 1012:                     . 'border="0" /></a>';
 1013:             }
 1014:         }
 1015:     }
 1016:     
 1017:     if ($resource->getErrors()) {
 1018:         my $errors = $resource->getErrors();
 1019:         foreach (split(/,/, $errors)) {
 1020:             if ($_) {
 1021:                 $errorHTML .= '&nbsp;<a href="/adm/email?display='
 1022:                     . &Apache::lonnet::escape($_) . '">'
 1023:                     . '<img src="/adm/lonMisc/bomb.gif" '
 1024:                     . 'border="0" /></a>';
 1025:             }
 1026:         }
 1027:     }
 1028: 
 1029:     if ($params->{'multipart'} && $part != '0') {
 1030: 	$discussionHTML = $feedbackHTML = $errorHTML = '';
 1031:     }
 1032: 
 1033:     return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";
 1034: 
 1035: }
 1036: sub render_quick_status {
 1037:     my ($resource, $part, $params) = @_;
 1038:     my $result = "";
 1039:     my $firstDisplayed = !$params->{'condensed'} && 
 1040:         $params->{'multipart'} && $part eq "0";
 1041: 
 1042:     my $link = $params->{"resourceLink"};
 1043:     my $linkopen = "<a href='$link'>";
 1044:     my $linkclose = "</a>";
 1045: 
 1046:     if ($resource->is_problem() &&
 1047:         !$firstDisplayed) {
 1048: 	
 1049:         my $icon = $statusIconMap{$resource->simpleStatus($part)};
 1050:         my $alt = $iconAltTags{$icon};
 1051:         if ($icon) {
 1052:             $result .= "<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";
 1053:         } else {
 1054:             $result .= "<td width='30'>&nbsp;</td>\n";
 1055:         }
 1056:     } else { # not problem, no icon
 1057:         $result .= "<td width='30'>&nbsp;</td>\n";
 1058:     }
 1059: 
 1060:     return $result;
 1061: }
 1062: sub render_long_status {
 1063:     my ($resource, $part, $params) = @_;
 1064:     my $result = "<td align='right' valign='center'>\n";
 1065:     my $firstDisplayed = !$params->{'condensed'} && 
 1066:         $params->{'multipart'} && $part eq "0";
 1067:                 
 1068:     my $color;
 1069:     if ($resource->is_problem()) {
 1070:         $color = $colormap{$resource->status};
 1071:         
 1072:         if (dueInLessThen24Hours($resource, $part) ||
 1073:             lastTry($resource, $part)) {
 1074:             $color = $hurryUpColor;
 1075:         }
 1076:     }
 1077:     
 1078:     if ($resource->kind() eq "res" &&
 1079:         $resource->is_problem() &&
 1080:         !$firstDisplayed) {
 1081:         if ($color) {$result .= "<font color=\"$color\"><b>"; }
 1082:         $result .= getDescription($resource, $part);
 1083:         if ($color) {$result .= "</b></font>"; }
 1084:     }
 1085:     if ($resource->is_map() && advancedUser() && $resource->randompick()) {
 1086:         $result .= '(randomly select ' . $resource->randompick() .')';
 1087:     }
 1088: 
 1089:     # Debugging code
 1090:     #$result .= " " . $resource->awarded($part) . '/' . $resource->weight($part) .
 1091:     #	' - Part: ' . $part;
 1092: 
 1093:     $result .= "</td>\n";
 1094:     
 1095:     return $result;
 1096: }
 1097: 
 1098: # Colors obtained by taking the icons, matching the colors, and
 1099: # possibly reducing the Value (HSV) of the color, if it's too bright
 1100: # for text, generally by one third or so.
 1101: my %statusColors = 
 1102:     (
 1103:      $resObj->CLOSED => '#000000',
 1104:      $resObj->OPEN   => '#998b13',
 1105:      $resObj->CORRECT => '#26933f',
 1106:      $resObj->INCORRECT => '#c48207',
 1107:      $resObj->ATTEMPTED => '#a87510',
 1108:      $resObj->ERROR => '#000000'
 1109:      );
 1110: my %statusStrings = 
 1111:     (
 1112:      $resObj->CLOSED => 'Not yet open',
 1113:      $resObj->OPEN   => 'Open',
 1114:      $resObj->CORRECT => 'Correct',
 1115:      $resObj->INCORRECT => 'Incorrect',
 1116:      $resObj->ATTEMPTED => 'Attempted',
 1117:      $resObj->ERROR => 'Network Error'
 1118:      );
 1119: my @statuses = ($resObj->CORRECT, $resObj->ATTEMPTED, $resObj->INCORRECT, $resObj->OPEN, $resObj->CLOSED, $resObj->ERROR);
 1120: 
 1121: use Data::Dumper;
 1122: sub render_parts_summary_status {
 1123:     my ($resource, $part, $params) = @_;
 1124:     if (!$resource->is_problem()) { return '<td></td>'; }
 1125:     if ($params->{showParts}) { 
 1126: 	return '<td></td>';
 1127:     }
 1128: 
 1129:     my $td = "<td align='right'>\n";
 1130:     my $endtd = "</td>\n";
 1131: 
 1132:     # If there is a single part, just show the simple status
 1133:     if ($resource->singlepart()) {
 1134: 	my $status = $resource->simpleStatus('0');
 1135: 	return $td . "<font color='" . $statusColors{$status} . "'>"
 1136: 	    . $statusStrings{$status} . "</font>" . $endtd;
 1137:     }
 1138: 
 1139:     # Now we can be sure the $part doesn't really matter.
 1140:     my $statusCount = $resource->simpleStatusCount();
 1141:     my @counts;
 1142:     foreach my $status(@statuses) {
 1143: 	# decouple display order from the simpleStatusCount order
 1144: 	my $slot = Apache::lonnavmaps::resource::statusToSlot($status);
 1145: 	if ($statusCount->[$slot]) {
 1146: 	    push @counts, "<font color='" . $statusColors{$status} .
 1147: 		"'>" . $statusCount->[$slot] . ' '
 1148: 		. $statusStrings{$status} . "</font>";
 1149: 	}
 1150:     }
 1151: 
 1152:     return $td . $resource->countParts() . ' parts: ' . join (', ', @counts) . $endtd;
 1153: }
 1154: 
 1155: my @preparedColumns = (\&render_resource, \&render_communication_status,
 1156:                        \&render_quick_status, \&render_long_status,
 1157: 		       \&render_parts_summary_status);
 1158: 
 1159: sub setDefault {
 1160:     my ($val, $default) = @_;
 1161:     if (!defined($val)) { return $default; }
 1162:     return $val;
 1163: }
 1164: 
 1165: sub render {
 1166:     my $args = shift;
 1167:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
 1168:     my $result = '';
 1169: 
 1170:     # Configure the renderer.
 1171:     my $cols = $args->{'cols'};
 1172:     if (!defined($cols)) {
 1173:         # no columns, no nav maps.
 1174:         return '';
 1175:     }
 1176:     my $mustCloseNavMap = 0;
 1177:     my $navmap;
 1178:     if (defined($args->{'navmap'})) {
 1179:         $navmap = $args->{'navmap'};
 1180:     }
 1181: 
 1182:     my $r = $args->{'r'};
 1183:     my $queryString = $args->{'queryString'};
 1184:     my $jump = $args->{'jump'};
 1185:     my $here = $args->{'here'};
 1186:     my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
 1187:     my $currentJumpDelta = 2; # change this to change how many resources are displayed
 1188:                              # before the current resource when using #current
 1189: 
 1190:     # If we were passed 'here' information, we are not rendering
 1191:     # after a folder manipulation, and we were not passed an
 1192:     # iterator, make sure we open the folders to show the "here"
 1193:     # marker
 1194:     my $filterHash = {};
 1195:     # Figure out what we're not displaying
 1196:     foreach (split(/\,/, $ENV{"form.filter"})) {
 1197:         if ($_) {
 1198:             $filterHash->{$_} = "1";
 1199:         }
 1200:     }
 1201: 
 1202:     # Filter: Remember filter function and add our own filter: Refuse
 1203:     # to show hidden resources unless the user can see them.
 1204:     my $userCanSeeHidden = advancedUser();
 1205:     my $filterFunc = setDefault($args->{'filterFunc'},
 1206:                                 sub {return 1;});
 1207:     if (!$userCanSeeHidden) {
 1208:         # Without renaming the filterfunc, the server seems to go into
 1209:         # an infinite loop
 1210:         my $oldFilterFunc = $filterFunc;
 1211:         $filterFunc = sub { my $res = shift; return !$res->randomout() && 
 1212:                                 &$oldFilterFunc($res);};
 1213:     }
 1214: 
 1215:     my $condition = 0;
 1216:     if ($ENV{'form.condition'}) {
 1217:         $condition = 1;
 1218:     }
 1219: 
 1220:     if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
 1221:         # Step 1: Check to see if we have a navmap
 1222:         if (!defined($navmap)) {
 1223:             $navmap = Apache::lonnavmaps::navmap->new();
 1224:             $mustCloseNavMap = 1;
 1225:         }
 1226: 
 1227:         # Step two: Locate what kind of here marker is necessary
 1228:         # Determine where the "here" marker is and where the screen jumps to.
 1229: 
 1230:         if ($ENV{'form.postsymb'}) {
 1231:             $here = $jump = $ENV{'form.postsymb'};
 1232:         } elsif ($ENV{'form.postdata'}) {
 1233:             # couldn't find a symb, is there a URL?
 1234:             my $currenturl = $ENV{'form.postdata'};
 1235:             #$currenturl=~s/^http\:\/\///;
 1236:             #$currenturl=~s/^[^\/]+//;
 1237:             
 1238:             $here = $jump = &Apache::lonnet::symbread($currenturl);
 1239:         }
 1240: 
 1241:         # Step three: Ensure the folders are open
 1242:         my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
 1243:         my $curRes;
 1244:         my $found = 0;
 1245:         
 1246:         # We only need to do this if we need to open the maps to show the
 1247:         # current position. This will change the counter so we can't count
 1248:         # for the jump marker with this loop.
 1249:         while (($curRes = $mapIterator->next()) && !$found) {
 1250:             if (ref($curRes) && $curRes->symb() eq $here) {
 1251:                 my $mapStack = $mapIterator->getStack();
 1252:                 
 1253:                 # Ensure the parent maps are open
 1254:                 for my $map (@{$mapStack}) {
 1255:                     if ($condition) {
 1256:                         undef $filterHash->{$map->map_pc()};
 1257:                     } else {
 1258:                         $filterHash->{$map->map_pc()} = 1;
 1259:                     }
 1260:                 }
 1261:                 $found = 1;
 1262:             }
 1263:         }            
 1264:     }        
 1265: 
 1266:     if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
 1267:         # If this is a click on a folder or something, we want to preserve the "here"
 1268:         # from the querystring, and get the new "jump" marker
 1269:         $here = $ENV{'form.here'};
 1270:         $jump = $ENV{'form.jump'};
 1271:     } 
 1272:     
 1273:     my $it = $args->{'iterator'};
 1274:     if (!defined($it)) {
 1275:         # Construct a default iterator based on $ENV{'form.'} information
 1276:         
 1277:         # Step 1: Check to see if we have a navmap
 1278:         if (!defined($navmap)) {
 1279:             $navmap = Apache::lonnavmaps::navmap->new();
 1280:             $mustCloseNavMap = 1;
 1281:         }
 1282: 
 1283:         # See if we're being passed a specific map
 1284:         if ($args->{'iterator_map'}) {
 1285:             my $map = $args->{'iterator_map'};
 1286:             $map = $navmap->getResourceByUrl($map);
 1287:             my $firstResource = $map->map_start();
 1288:             my $finishResource = $map->map_finish();
 1289: 
 1290:             $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
 1291:         } else {
 1292:             $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
 1293:         }
 1294:     }
 1295:     
 1296:     # (re-)Locate the jump point, if any
 1297:     # Note this does not take filtering or hidden into account... need
 1298:     # to be fixed?
 1299:     my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
 1300:     my $curRes;
 1301:     my $foundJump = 0;
 1302:     my $counter = 0;
 1303:     
 1304:     while (($curRes = $mapIterator->next()) && !$foundJump) {
 1305:         if (ref($curRes)) { $counter++; }
 1306:         
 1307:         if (ref($curRes) && $jump eq $curRes->symb()) {
 1308:             
 1309:             # This is why we have to use the main iterator instead of the
 1310:             # potentially faster DFS: The count has to be the same, so
 1311:             # the order has to be the same, which DFS won't give us.
 1312:             $args->{'currentJumpIndex'} = $counter;
 1313:             $foundJump = 1;
 1314:         }
 1315:     }
 1316: 
 1317:     my $showParts = setDefault($args->{'showParts'}, 1);
 1318:     my $condenseParts = setDefault($args->{'condenseParts'}, 1);
 1319:     # keeps track of when the current resource is found,
 1320:     # so we can back up a few and put the anchor above the
 1321:     # current resource
 1322:     my $printKey = $args->{'printKey'};
 1323:     my $printCloseAll = $args->{'printCloseAll'};
 1324:     if (!defined($printCloseAll)) { $printCloseAll = 1; }
 1325:     
 1326:     # Print key?
 1327:     if ($printKey) {
 1328:         $result .= '<table border="0" cellpadding="2" cellspacing="0">';
 1329:         my $date=localtime;
 1330:         $result.='<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>';
 1331:         if ($navmap->{LAST_CHECK}) {
 1332:             $result .= 
 1333:                 '<img src="/adm/lonMisc/chat.gif"> '.&mt('New discussion since').' '.
 1334:                 strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
 1335:                 '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
 1336:                 '<img src="/adm/lonMisc/feedback.gif"> '.&mt('New message (click to open)').'<p>'.
 1337:                 '</td>'; 
 1338:         } else {
 1339:             $result .= '<td align="center" valign="bottom">&nbsp;&nbsp;'.
 1340:                 '<img src="/adm/lonMisc/chat.gif"> '.&mt('Discussions').'</td><td align="center" valign="bottom">'.
 1341:                 '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> '.&mt('New message (click to open)').
 1342:                 '</td>'; 
 1343:         }
 1344: 
 1345:         $result .= '</tr></table>';
 1346:     }
 1347: 
 1348:     if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
 1349:         if ($condition) {
 1350:             $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
 1351:                 "&here=" . Apache::lonnet::escape($here) .
 1352:                 "\">".&mt('Close All Folders')."</a>";
 1353:         } else {
 1354:             $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
 1355:                 "&here=" . Apache::lonnet::escape($here) . 
 1356:                 "\">".&mt('Open All Folders')."</a>";
 1357:         }
 1358:         $result .= "<br /><br />\n";
 1359:     }    
 1360: 
 1361:     if ($r) {
 1362:         $r->print($result);
 1363:         $r->rflush();
 1364:         $result = "";
 1365:     }
 1366:     # End parameter setting
 1367:             
 1368:     # Data
 1369:     $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
 1370:     my $res = "Apache::lonnavmaps::resource";
 1371:     my %condenseStatuses =
 1372:         ( $res->NETWORK_FAILURE    => 1,
 1373:           $res->NOTHING_SET        => 1,
 1374:           $res->CORRECT            => 1 );
 1375:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
 1376: 
 1377:     # Shared variables
 1378:     $args->{'counter'} = 0; # counts the rows
 1379:     $args->{'indentLevel'} = 0;
 1380:     $args->{'isNewBranch'} = 0;
 1381:     $args->{'condensed'} = 0;    
 1382:     $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
 1383:     $args->{'displayedHereMarker'} = 0;
 1384: 
 1385:     # If we're suppressing empty sequences, look for them here. Use DFS for speed,
 1386:     # since structure actually doesn't matter, except what map has what resources.
 1387:     if ($args->{'suppressEmptySequences'}) {
 1388:         my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
 1389:                                                          $it->{FIRST_RESOURCE},
 1390:                                                          $it->{FINISH_RESOURCE},
 1391:                                                          {}, undef, 1);
 1392:         my $depth = 0;
 1393:         $dfsit->next();
 1394:         my $curRes = $dfsit->next();
 1395:         while ($depth > -1) {
 1396:             if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
 1397:             if ($curRes == $dfsit->END_MAP()) { $depth--; }
 1398: 
 1399:             if (ref($curRes)) { 
 1400:                 # Parallel pre-processing: Do sequences have non-filtered-out children?
 1401:                 if ($curRes->is_map()) {
 1402:                     $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
 1403:                     # Sequences themselves do not count as visible children,
 1404:                     # unless those sequences also have visible children.
 1405:                     # This means if a sequence appears, there's a "promise"
 1406:                     # that there's something under it if you open it, somewhere.
 1407:                 } else {
 1408:                     # Not a sequence: if it's filtered, ignore it, otherwise
 1409:                     # rise up the stack and mark the sequences as having children
 1410:                     if (&$filterFunc($curRes)) {
 1411:                         for my $sequence (@{$dfsit->getStack()}) {
 1412:                             $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
 1413:                         }
 1414:                     }
 1415:                 }
 1416:             }
 1417:         } continue {
 1418:             $curRes = $dfsit->next();
 1419:         }
 1420:     }
 1421: 
 1422:     my $displayedJumpMarker = 0;
 1423:     # Set up iteration.
 1424:     my $now = time();
 1425:     my $in24Hours = $now + 24 * 60 * 60;
 1426:     my $rownum = 0;
 1427: 
 1428:     # export "here" marker information
 1429:     $args->{'here'} = $here;
 1430: 
 1431:     $args->{'indentLevel'} = -1; # first BEGIN_MAP takes this to 0
 1432:     while ($curRes = $it->next()) {
 1433:         # Maintain indentation level.
 1434:         if ($curRes == $it->BEGIN_MAP() ||
 1435:             $curRes == $it->BEGIN_BRANCH() ) {
 1436:             $args->{'indentLevel'}++;
 1437:         }
 1438:         if ($curRes == $it->END_MAP() ||
 1439:             $curRes == $it->END_BRANCH() ) {
 1440:             $args->{'indentLevel'}--;
 1441:         }
 1442:         # Notice new branches
 1443:         if ($curRes == $it->BEGIN_BRANCH()) {
 1444:             $args->{'isNewBranch'} = 1;
 1445:         }
 1446: 
 1447:         # If this isn't an actual resource, continue on
 1448:         if (!ref($curRes)) {
 1449:             next;
 1450:         }
 1451: 
 1452:         # If this has been filtered out, continue on
 1453:         if (!(&$filterFunc($curRes))) {
 1454:             $args->{'isNewBranch'} = 0; # Don't falsely remember this
 1455:             next;
 1456:         } 
 1457: 
 1458:         # If this is an empty sequence and we're filtering them, continue on
 1459:         if ($curRes->is_map() && $args->{'suppressEmptySequences'} &&
 1460:             !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) {
 1461:             next;
 1462:         }
 1463: 
 1464:         # If we're suppressing navmaps and this is a navmap, continue on
 1465:         if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
 1466:             next;
 1467:         }
 1468: 
 1469:         $args->{'counter'}++;
 1470: 
 1471:         # Does it have multiple parts?
 1472:         $args->{'multipart'} = 0;
 1473:         $args->{'condensed'} = 0;
 1474:         my @parts;
 1475:             
 1476:         # Decide what parts to show.
 1477:         if ($curRes->is_problem() && $showParts) {
 1478:             @parts = @{$curRes->parts()};
 1479:             $args->{'multipart'} = $curRes->multipart();
 1480:             
 1481:             if ($condenseParts) { # do the condensation
 1482:                 if (!$curRes->opendate("0")) {
 1483:                     @parts = ();
 1484:                     $args->{'condensed'} = 1;
 1485:                 }
 1486:                 if (!$args->{'condensed'}) {
 1487:                     # Decide whether to condense based on similarity
 1488:                     my $status = $curRes->status($parts[0]);
 1489:                     my $due = $curRes->duedate($parts[0]);
 1490:                     my $open = $curRes->opendate($parts[0]);
 1491:                     my $statusAllSame = 1;
 1492:                     my $dueAllSame = 1;
 1493:                     my $openAllSame = 1;
 1494:                     for (my $i = 1; $i < scalar(@parts); $i++) {
 1495:                         if ($curRes->status($parts[$i]) != $status){
 1496:                             $statusAllSame = 0;
 1497:                         }
 1498:                         if ($curRes->duedate($parts[$i]) != $due ) {
 1499:                             $dueAllSame = 0;
 1500:                         }
 1501:                         if ($curRes->opendate($parts[$i]) != $open) {
 1502:                             $openAllSame = 0;
 1503:                         }
 1504:                     }
 1505:                     # $*allSame is true if all the statuses were
 1506:                     # the same. Now, if they are all the same and
 1507:                     # match one of the statuses to condense, or they
 1508:                     # are all open with the same due date, or they are
 1509:                     # all OPEN_LATER with the same open date, display the
 1510:                     # status of the first non-zero part (to get the 'correct'
 1511:                     # status right, since 0 is never 'correct' or 'open').
 1512:                     if (($statusAllSame && defined($condenseStatuses{$status})) ||
 1513:                         ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
 1514:                         ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
 1515:                         @parts = ($parts[0]);
 1516:                         $args->{'condensed'} = 1;
 1517:                     }
 1518:                 }
 1519: 		# Multipart problem with one part: always "condense" (happens
 1520: 		#  to match the desirable behavior)
 1521: 		if ($curRes->countParts() == 1) {
 1522: 		    @parts = ($parts[0]);
 1523: 		    $args->{'condensed'} = 1;
 1524: 		}
 1525:             }
 1526:         } 
 1527:             
 1528:         # If the multipart problem was condensed, "forget" it was multipart
 1529:         if (scalar(@parts) == 1) {
 1530:             $args->{'multipart'} = 0;
 1531:         } else {
 1532:             # Add part 0 so we display it correctly.
 1533:             unshift @parts, '0';
 1534:         }
 1535: 
 1536:         # Now, we've decided what parts to show. Loop through them and
 1537:         # show them.
 1538:         foreach my $part (@parts) {
 1539:             $rownum ++;
 1540:             my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
 1541:             
 1542:             $result .= "  <tr bgcolor='$backgroundColor'>\n";
 1543: 
 1544:             # Set up some data about the parts that the cols might want
 1545:             my $filter = $it->{FILTER};
 1546:             my $stack = $it->getStack();
 1547:             my $src = getLinkForResource($stack);
 1548:             
 1549:             my $srcHasQuestion = $src =~ /\?/;
 1550:             $args->{"resourceLink"} = $src.
 1551:                 ($srcHasQuestion?'&':'?') .
 1552:                 'symb=' . &Apache::lonnet::escape($curRes->symb());
 1553:             
 1554:             # Now, display each column.
 1555:             foreach my $col (@$cols) {
 1556:                 my $colHTML = '';
 1557:                 if (ref($col)) {
 1558:                     $colHTML .= &$col($curRes, $part, $args);
 1559:                 } else {
 1560:                     $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
 1561:                 }
 1562: 
 1563:                 # If this is the first column and it's time to print
 1564:                 # the anchor, do so
 1565:                 if ($col == $cols->[0] && 
 1566:                     $args->{'counter'} == $args->{'currentJumpIndex'} - 
 1567:                     $currentJumpDelta) {
 1568:                     # Jam the anchor after the <td> tag;
 1569:                     # necessary for valid HTML (which Mozilla requires)
 1570:                     $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
 1571:                     $displayedJumpMarker = 1;
 1572:                 }
 1573:                 $result .= $colHTML . "\n";
 1574:             }
 1575:             $result .= "    </tr>\n";
 1576:             $args->{'isNewBranch'} = 0;
 1577:         }
 1578: 
 1579:         if ($r && $rownum % 20 == 0) {
 1580:             $r->print($result);
 1581:             $result = "";
 1582:             $r->rflush();
 1583:         }
 1584:     } continue {
 1585: 	if ($r) {
 1586: 	    # If we have the connection, make sure the user is still connected
 1587: 	    my $c = $r->connection;
 1588: 	    if ($c->aborted()) {
 1589: 		# Who cares what we do, nobody will see it anyhow.
 1590: 		return '';
 1591: 	    }
 1592: 	}
 1593:     }
 1594:     
 1595:     # Print out the part that jumps to #curloc if it exists
 1596:     # delay needed because the browser is processing the jump before
 1597:     # it finishes rendering, so it goes to the wrong place!
 1598:     # onload might be better, but this routine has no access to that.
 1599:     # On mozilla, the 0-millisecond timeout seems to prevent this;
 1600:     # it's quite likely this might fix other browsers, too, and 
 1601:     # certainly won't hurt anything.
 1602:     if ($displayedJumpMarker) {
 1603:         $result .= "<script>setTimeout(\"location += '#curloc';\", 0)</script>\n";
 1604:     }
 1605: 
 1606:     $result .= "</table>";
 1607:     
 1608:     if ($r) {
 1609:         $r->print($result);
 1610:         $result = "";
 1611:         $r->rflush();
 1612:     }
 1613:         
 1614:     if ($mustCloseNavMap) { $navmap->untieHashes(); } 
 1615: 
 1616:     return $result;
 1617: }
 1618: 
 1619: 1;
 1620: 
 1621: package Apache::lonnavmaps::navmap;
 1622: 
 1623: =pod
 1624: 
 1625: =head1 Object: Apache::lonnavmaps::navmap
 1626: 
 1627: =head2 Overview
 1628: 
 1629: The navmap object's job is to provide access to the resources
 1630: in the course as Apache::lonnavmaps::resource objects, and to
 1631: query and manage the relationship between those resource objects.
 1632: 
 1633: Generally, you'll use the navmap object in one of three basic ways.
 1634: In order of increasing complexity and power:
 1635: 
 1636: =over 4
 1637: 
 1638: =item * C<$navmap-E<gt>getByX>, where X is B<Id>, B<Symb>, B<Url> or B<MapPc>. This provides
 1639:     various ways to obtain resource objects, based on various identifiers.
 1640:     Use this when you want to request information about one object or 
 1641:     a handful of resources you already know the identities of, from some
 1642:     other source. For more about Ids, Symbs, and MapPcs, see the
 1643:     Resource documentation. Note that Url should be a B<last resort>,
 1644:     not your first choice; it only works when there is only one
 1645:     instance of the resource in the course, which only applies to
 1646:     maps, and even that may change in the future.
 1647: 
 1648: =item * C<my @resources = $navmap-E<gt>retrieveResources(args)>. This
 1649:     retrieves resources matching some criterion and returns them
 1650:     in a flat array, with no structure information. Use this when
 1651:     you are manipulating a series of resources, based on what map
 1652:     the are in, but do not care about branching, or exactly how
 1653:     the maps and resources are related. This is the most common case.
 1654: 
 1655: =item * C<$it = $navmap-E<gt>getIterator(args)>. This allows you traverse
 1656:     the course's navmap in various ways without writing the traversal
 1657:     code yourself. See iterator documentation below. Use this when
 1658:     you need to know absolutely everything about the course, including
 1659:     branches and the precise relationship between maps and resources.
 1660: 
 1661: =back
 1662: 
 1663: =head2 Creation And Destruction
 1664: 
 1665: To create a navmap object, use the following function:
 1666: 
 1667: =over 4
 1668: 
 1669: =item * B<Apache::lonnavmaps::navmap-E<gt>new>():
 1670: 
 1671: Creates a new navmap object. Returns the navmap object if this is
 1672: successful, or B<undef> if not.
 1673: 
 1674: =back
 1675: 
 1676: When you are done with the $navmap object, you I<must> call 
 1677: $navmap->untieHashes(), or you'll prevent the current user from using that 
 1678: course until the web server is restarted. (!)
 1679: 
 1680: =head2 Methods
 1681: 
 1682: =over 4
 1683: 
 1684: =item * B<getIterator>(first, finish, filter, condition):
 1685: 
 1686: See iterator documentation below.
 1687: 
 1688: =cut
 1689: 
 1690: use strict;
 1691: use GDBM_File;
 1692: 
 1693: sub new {
 1694:     # magic invocation to create a class instance
 1695:     my $proto = shift;
 1696:     my $class = ref($proto) || $proto;
 1697:     my $self = {};
 1698: 
 1699:     # Resource cache stores navmap resources as we reference them. We generate
 1700:     # them on-demand so we don't pay for creating resources unless we use them.
 1701:     $self->{RESOURCE_CACHE} = {};
 1702: 
 1703:     # Network failure flag, if we accessed the course or user opt and
 1704:     # failed
 1705:     $self->{NETWORK_FAILURE} = 0;
 1706: 
 1707:     # tie the nav hash
 1708: 
 1709:     my %navmaphash;
 1710:     my %parmhash;
 1711:     my $courseFn = $ENV{"request.course.fn"};
 1712:     if (!(tie(%navmaphash, 'GDBM_File', "${courseFn}.db",
 1713:               &GDBM_READER(), 0640))) {
 1714:         return undef;
 1715:     }
 1716:     
 1717:     if (!(tie(%parmhash, 'GDBM_File', "${courseFn}_parms.db",
 1718:               &GDBM_READER(), 0640)))
 1719:     {
 1720:         untie %{$self->{PARM_HASH}};
 1721:         return undef;
 1722:     }
 1723: 
 1724:     $self->{NAV_HASH} = \%navmaphash;
 1725:     $self->{PARM_HASH} = \%parmhash;
 1726:     $self->{PARM_CACHE} = {};
 1727: 
 1728:     bless($self);
 1729:         
 1730:     return $self;
 1731: }
 1732: 
 1733: sub generate_course_user_opt {
 1734:     my $self = shift;
 1735:     if ($self->{COURSE_USER_OPT_GENERATED}) { return; }
 1736: 
 1737:     my $uname=$ENV{'user.name'};
 1738:     my $udom=$ENV{'user.domain'};
 1739:     my $uhome=$ENV{'user.home'};
 1740:     my $cid=$ENV{'request.course.id'};
 1741:     my $chome=$ENV{'course.'.$cid.'.home'};
 1742:     my ($cdom,$cnum)=split(/\_/,$cid);
 1743:     
 1744:     my $userprefix=$uname.'_'.$udom.'_';
 1745:     
 1746:     my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
 1747:     unless ($uhome eq 'no_host') { 
 1748: # ------------------------------------------------- Get coursedata (if present)
 1749: 	unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1750: 	    my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1751: 					     ':resourcedata',$chome);
 1752: 	    # Check for network failure
 1753: 	    if ( $reply =~ /no.such.host/i || $reply =~ /con_lost/i) {
 1754: 		$self->{NETWORK_FAILURE} = 1;
 1755: 	    } elsif ($reply!~/^error\:/) {
 1756: 		$courserdatas{$cid}=$reply;
 1757: 		$courserdatas{$cid.'.last_cache'}=time;
 1758: 	    }
 1759: 	}
 1760: 	foreach (split(/\&/,$courserdatas{$cid})) {
 1761: 	    my ($name,$value)=split(/\=/,$_);
 1762: 	    $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 1763: 		&Apache::lonnet::unescape($value);
 1764: 	}
 1765: # --------------------------------------------------- Get userdata (if present)
 1766: 	unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 1767: 	    my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 1768: 	    if ($reply!~/^error\:/) {
 1769: 		$userrdatas{$uname.'___'.$udom}=$reply;
 1770: 		$userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 1771: 	    }
 1772: 	    # check to see if network failed
 1773: 	    elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
 1774: 	    {
 1775: 		$self->{NETWORK_FAILURE} = 1;
 1776: 	    }
 1777: 	}
 1778: 	foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 1779: 	    my ($name,$value)=split(/\=/,$_);
 1780: 	    $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 1781: 		&Apache::lonnet::unescape($value);
 1782: 	}
 1783: 	$self->{COURSE_OPT} = \%courseopt;
 1784: 	$self->{USER_OPT} = \%useropt;
 1785:     }
 1786: 
 1787:     $self->{COURSE_USER_OPT_GENERATED} = 1;
 1788:     
 1789:     return;
 1790: }
 1791: 
 1792: sub generate_email_discuss_status {
 1793:     my $self = shift;
 1794:     if ($self->{EMAIL_DISCUSS_GENERATED}) { return; }
 1795: 
 1796:     my $cid=$ENV{'request.course.id'};
 1797:     my ($cdom,$cnum)=split(/\_/,$cid);
 1798:     
 1799:     my %emailstatus = &Apache::lonnet::dump('email_status');
 1800:     my $logoutTime = $emailstatus{'logout'};
 1801:     my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
 1802:     $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
 1803: 			   $courseLeaveTime : $logoutTime);
 1804:     my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
 1805: 					       $cdom, $cnum);
 1806:     my %feedback=();
 1807:     my %error=();
 1808:     my $keys = &Apache::lonnet::reply('keys:'.
 1809: 				      $ENV{'user.domain'}.':'.
 1810: 				      $ENV{'user.name'}.':nohist_email',
 1811: 				      $ENV{'user.home'});
 1812:     
 1813:     foreach my $msgid (split(/\&/, $keys)) {
 1814: 	$msgid=&Apache::lonnet::unescape($msgid);
 1815: 	my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
 1816: 	if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
 1817: 	    my ($what,$url)=($1,$2);
 1818: 	    my %status=
 1819: 		&Apache::lonnet::get('email_status',[$msgid]);
 1820: 	    if ($status{$msgid}=~/^error\:/) { 
 1821: 		$status{$msgid}=''; 
 1822: 	    }
 1823: 	    
 1824: 	    if (($status{$msgid} eq 'new') || 
 1825: 		(!$status{$msgid})) { 
 1826: 		if ($what eq 'Error') {
 1827: 		    $error{$url}.=','.$msgid; 
 1828: 		} else {
 1829: 		    $feedback{$url}.=','.$msgid;
 1830: 		}
 1831: 	    }
 1832: 	}
 1833:     }
 1834:     
 1835:     $self->{FEEDBACK} = \%feedback;
 1836:     $self->{ERROR_MSG} = \%error; # what is this? JB
 1837:     $self->{DISCUSSION_TIME} = \%discussiontime;
 1838:     $self->{EMAIL_STATUS} = \%emailstatus;
 1839:     
 1840:     $self->{EMAIL_DISCUSS_GENERATED} = 1;
 1841: }
 1842: 
 1843: sub get_user_data {
 1844:     my $self = shift;
 1845:     if ($self->{RETRIEVED_USER_DATA}) { return; }
 1846: 
 1847:     # Retrieve performance data on problems
 1848:     my %student_data = Apache::lonnet::currentdump($ENV{'request.course.id'},
 1849: 						   $ENV{'user.domain'},
 1850: 						   $ENV{'user.name'});
 1851:     $self->{STUDENT_DATA} = \%student_data;
 1852: 
 1853:     $self->{RETRIEVED_USER_DATA} = 1;
 1854: }
 1855: 
 1856: # Internal function: Takes a key to look up in the nav hash and implements internal
 1857: # memory caching of that key.
 1858: sub navhash {
 1859:     my $self = shift; my $key = shift;
 1860:     return $self->{NAV_HASH}->{$key};
 1861: }
 1862: 
 1863: =pod
 1864: 
 1865: =item * B<courseMapDefined>(): Returns true if the course map is defined, 
 1866:     false otherwise. Undefined course maps indicate an error somewhere in
 1867:     LON-CAPA, and you will not be able to proceed with using the navmap.
 1868:     See the B<NAV> screen for an example of using this.
 1869: 
 1870: =cut
 1871: 
 1872: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 1873: sub courseMapDefined {
 1874:     my $self = shift;
 1875:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
 1876: 
 1877:     my $firstres = $self->navhash("map_start_$uri");
 1878:     my $lastres = $self->navhash("map_finish_$uri");
 1879:     return $firstres && $lastres;
 1880: }
 1881: 
 1882: sub getIterator {
 1883:     my $self = shift;
 1884:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
 1885:                                                      shift, undef, shift);
 1886:     return $iterator;
 1887: }
 1888: 
 1889: # unties the hash when done
 1890: sub untieHashes {
 1891:     my $self = shift;
 1892:     untie %{$self->{NAV_HASH}};
 1893:     untie %{$self->{PARM_HASH}};
 1894: }
 1895: 
 1896: # Private method: Does the given resource (as a symb string) have
 1897: # current discussion? Returns 0 if chat/mail data not extracted.
 1898: sub hasDiscussion {
 1899:     my $self = shift;
 1900:     my $symb = shift;
 1901:     
 1902:     $self->generate_email_discuss_status();
 1903: 
 1904:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 1905: 
 1906:     #return defined($self->{DISCUSSION_TIME}->{$symb});
 1907:     return $self->{DISCUSSION_TIME}->{$symb} >
 1908:            $self->{LAST_CHECK};
 1909: }
 1910: 
 1911: # Private method: Does the given resource (as a symb string) have
 1912: # current feedback? Returns the string in the feedback hash, which
 1913: # will be false if it does not exist.
 1914: sub getFeedback { 
 1915:     my $self = shift;
 1916:     my $symb = shift;
 1917: 
 1918:     $self->generate_email_discuss_status();
 1919: 
 1920:     if (!defined($self->{FEEDBACK})) { return ""; }
 1921:     
 1922:     return $self->{FEEDBACK}->{$symb};
 1923: }
 1924: 
 1925: # Private method: Get the errors for that resource (by source).
 1926: sub getErrors { 
 1927:     my $self = shift;
 1928:     my $src = shift;
 1929: 
 1930:     $self->generate_email_discuss_status();
 1931: 
 1932:     if (!defined($self->{ERROR_MSG})) { return ""; }
 1933:     return $self->{ERROR_MSG}->{$src};
 1934: }
 1935: 
 1936: =pod
 1937: 
 1938: =item * B<getById>(id):
 1939: 
 1940: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
 1941: object for that resource. This method, or other methods that use it
 1942: (as in the resource object) is the only proper way to obtain a
 1943: resource object.
 1944: 
 1945: =item * B<getBySymb>(symb):
 1946: 
 1947: Based on the symb of the resource, get a resource object for that
 1948: resource. This is one of the proper ways to get a resource object.
 1949: 
 1950: =item * B<getMapByMapPc>(map_pc):
 1951: 
 1952: Based on the map_pc of the resource, get a resource object for
 1953: the given map. This is one of the proper ways to get a resource object.
 1954: 
 1955: =cut
 1956: 
 1957: # The strategy here is to cache the resource objects, and only construct them
 1958: # as we use them. The real point is to prevent reading any more from the tied
 1959: # hash then we have to, which should hopefully alleviate speed problems.
 1960: 
 1961: sub getById {
 1962:     my $self = shift;
 1963:     my $id = shift;
 1964: 
 1965:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 1966:     {
 1967:         return $self->{RESOURCE_CACHE}->{$id};
 1968:     }
 1969: 
 1970:     # resource handles inserting itself into cache.
 1971:     # Not clear why the quotes are necessary, but as of this
 1972:     # writing it doesn't work without them.
 1973:     return "Apache::lonnavmaps::resource"->new($self, $id);
 1974: }
 1975: 
 1976: sub getBySymb {
 1977:     my $self = shift;
 1978:     my $symb = shift;
 1979:     my ($mapUrl, $id, $filename) = &Apache::lonnet::decode_symb($symb);
 1980:     my $map = $self->getResourceByUrl($mapUrl);
 1981:     return $self->getById($map->map_pc() . '.' . $id);
 1982: }
 1983: 
 1984: sub getByMapPc {
 1985:     my $self = shift;
 1986:     my $map_pc = shift;
 1987:     my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
 1988:     $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
 1989:     return $self->getById($map_id);
 1990: }
 1991: 
 1992: =pod
 1993: 
 1994: =item * B<firstResource>():
 1995: 
 1996: Returns a resource object reference corresponding to the first
 1997: resource in the navmap.
 1998: 
 1999: =cut
 2000: 
 2001: sub firstResource {
 2002:     my $self = shift;
 2003:     my $firstResource = $self->navhash('map_start_' .
 2004:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
 2005:     return $self->getById($firstResource);
 2006: }
 2007: 
 2008: =pod
 2009: 
 2010: =item * B<finishResource>():
 2011: 
 2012: Returns a resource object reference corresponding to the last resource
 2013: in the navmap.
 2014: 
 2015: =cut
 2016: 
 2017: sub finishResource {
 2018:     my $self = shift;
 2019:     my $firstResource = $self->navhash('map_finish_' .
 2020:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
 2021:     return $self->getById($firstResource);
 2022: }
 2023: 
 2024: # Parmval reads the parm hash and cascades the lookups. parmval_real does
 2025: # the actual lookup; parmval caches the results.
 2026: sub parmval {
 2027:     my $self = shift;
 2028:     my ($what,$symb)=@_;
 2029:     my $hashkey = $what."|||".$symb;
 2030: 
 2031:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
 2032:         return $self->{PARM_CACHE}->{$hashkey};
 2033:     }
 2034: 
 2035:     my $result = $self->parmval_real($what, $symb);
 2036:     $self->{PARM_CACHE}->{$hashkey} = $result;
 2037:     return $result;
 2038: }
 2039: 
 2040: sub parmval_real {
 2041:     my $self = shift;
 2042:     my ($what,$symb,$recurse) = @_;
 2043: 
 2044:     # Make sure the {USER_OPT} and {COURSE_OPT} hashes are populated
 2045:     $self->generate_course_user_opt();
 2046: 
 2047:     my $cid=$ENV{'request.course.id'};
 2048:     my $csec=$ENV{'request.course.sec'};
 2049:     my $uname=$ENV{'user.name'};
 2050:     my $udom=$ENV{'user.domain'};
 2051: 
 2052:     unless ($symb) { return ''; }
 2053:     my $result='';
 2054: 
 2055:     my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
 2056: 
 2057: # ----------------------------------------------------- Cascading lookup scheme
 2058:     my $rwhat=$what;
 2059:     $what=~s/^parameter\_//;
 2060:     $what=~s/\_/\./;
 2061: 
 2062:     my $symbparm=$symb.'.'.$what;
 2063:     my $mapparm=$mapname.'___(all).'.$what;
 2064:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 2065: 
 2066:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 2067:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 2068:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 2069: 
 2070:     my $courselevel= $usercourseprefix.'.'.$what;
 2071:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 2072:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 2073: 
 2074:     my $useropt = $self->{USER_OPT};
 2075:     my $courseopt = $self->{COURSE_OPT};
 2076:     my $parmhash = $self->{PARM_HASH};
 2077: 
 2078: # ---------------------------------------------------------- first, check user
 2079:     if ($uname and defined($useropt)) {
 2080:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
 2081:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
 2082:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
 2083:     }
 2084: 
 2085: # ------------------------------------------------------- second, check course
 2086:     if ($csec and defined($courseopt)) {
 2087:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
 2088:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
 2089:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
 2090:     }
 2091: 
 2092:     if (defined($courseopt)) {
 2093:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
 2094:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
 2095:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
 2096:     }
 2097: 
 2098: # ----------------------------------------------------- third, check map parms
 2099: 
 2100:     my $thisparm=$$parmhash{$symbparm};
 2101:     if (defined($thisparm)) { return $thisparm; }
 2102: 
 2103: # ----------------------------------------------------- fourth , check default
 2104: 
 2105:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
 2106:     if (defined($default)) { return $default}
 2107: 
 2108: # --------------------------------------------------- fifth , cascade up parts
 2109: 
 2110:     my ($space,@qualifier)=split(/\./,$rwhat);
 2111:     my $qualifier=join('.',@qualifier);
 2112:     unless ($space eq '0') {
 2113: 	my @parts=split(/_/,$space);
 2114: 	my $id=pop(@parts);
 2115: 	my $part=join('_',@parts);
 2116: 	if ($part eq '') { $part='0'; }
 2117: 	my $partgeneral=$self->parmval($part.".$qualifier",$symb,1);
 2118: 	if (defined($partgeneral)) { return $partgeneral; }
 2119:     }
 2120:     if ($recurse) { return undef; }
 2121:     my $pack_def=&Apache::lonnet::packages_tab_default($fn,'resource.'.$what);
 2122:     if (defined($pack_def)) { return $pack_def; }
 2123:     return '';
 2124: }
 2125: 
 2126: =pod
 2127: 
 2128: =item * B<getResourceByUrl>(url):
 2129: 
 2130: Retrieves a resource object by URL of the resource. If passed a
 2131: resource object, it will simply return it, so it is safe to use this
 2132: method in code like "$res = $navmap->getResourceByUrl($res)", if
 2133: you're not sure if $res is already an object, or just a URL. If the
 2134: resource appears multiple times in the course, only the first instance
 2135: will be returned. As a result, this is probably useful only for maps.
 2136: 
 2137: =item * B<retrieveResources>(map, filterFunc, recursive, bailout):
 2138: 
 2139: The map is a specification of a map to retreive the resources from,
 2140: either as a url or as an object. The filterFunc is a reference to a
 2141: function that takes a resource object as its one argument and returns
 2142: true if the resource should be included, or false if it should not
 2143: be. If recursive is true, the map will be recursively examined,
 2144: otherwise it will not be. If bailout is true, the function will return
 2145: as soon as it finds a resource, if false it will finish. By default,
 2146: the map is the top-level map of the course, filterFunc is a function
 2147: that always returns 1, recursive is true, bailout is false. The
 2148: resources will be returned in a list containing the resource objects
 2149: for the corresponding resources, with B<no structure information> in
 2150: the list; regardless of branching, recursion, etc., it will be a flat
 2151: list.
 2152: 
 2153: Thus, this is suitable for cases where you don't want the structure,
 2154: just a list of all resources. It is also suitable for finding out how
 2155: many resources match a given description; for this use, if all you
 2156: want to know is if I<any> resources match the description, the bailout
 2157: parameter will allow you to avoid potentially expensive enumeration of
 2158: all matching resources.
 2159: 
 2160: =item * B<hasResources>(map, filterFunc, recursive):
 2161: 
 2162: Convience method for
 2163: 
 2164:  scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
 2165: 
 2166: which will tell whether the map has resources matching the description
 2167: in the filter function.
 2168: 
 2169: =cut
 2170: 
 2171: sub getResourceByUrl {
 2172:     my $self = shift;
 2173:     my $resUrl = shift;
 2174: 
 2175:     if (ref($resUrl)) { return $resUrl; }
 2176: 
 2177:     $resUrl = &Apache::lonnet::clutter($resUrl);
 2178:     my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
 2179:     if ($resId =~ /,/) {
 2180:         $resId = (split (/,/, $resId))[0];
 2181:     }
 2182:     if (!$resId) { return ''; }
 2183:     return $self->getById($resId);
 2184: }
 2185: 
 2186: sub retrieveResources {
 2187:     my $self = shift;
 2188:     my $map = shift;
 2189:     my $filterFunc = shift;
 2190:     if (!defined ($filterFunc)) {
 2191:         $filterFunc = sub {return 1;};
 2192:     }
 2193:     my $recursive = shift;
 2194:     if (!defined($recursive)) { $recursive = 1; }
 2195:     my $bailout = shift;
 2196:     if (!defined($bailout)) { $bailout = 0; }
 2197: 
 2198:     # Create the necessary iterator.
 2199:     if (!ref($map)) { # assume it's a url of a map.
 2200:         $map = $self->getResourceByUrl($map);
 2201:     }
 2202: 
 2203:     # If nothing was passed, assume top-level map
 2204:     if (!$map) {
 2205: 	$map = $self->getById('0.0');
 2206:     }
 2207: 
 2208:     # Check the map's validity.
 2209:     if (!$map->is_map()) {
 2210:         # Oh, to throw an exception.... how I'd love that!
 2211:         return ();
 2212:     }
 2213: 
 2214:     # Get an iterator.
 2215:     my $it = $self->getIterator($map->map_start(), $map->map_finish(),
 2216:                                 undef, $recursive);
 2217: 
 2218:     my @resources = ();
 2219: 
 2220:     # Run down the iterator and collect the resources.
 2221:     my $curRes;
 2222: 
 2223:     while ($curRes = $it->next()) {
 2224:         if (ref($curRes)) {
 2225:             if (!&$filterFunc($curRes)) {
 2226:                 next;
 2227:             }
 2228: 
 2229:             push @resources, $curRes;
 2230: 
 2231:             if ($bailout) {
 2232:                 return @resources;
 2233:             }
 2234:         }
 2235: 
 2236:     }
 2237: 
 2238:     return @resources;
 2239: }
 2240: 
 2241: sub hasResource {
 2242:     my $self = shift;
 2243:     my $map = shift;
 2244:     my $filterFunc = shift;
 2245:     my $recursive = shift;
 2246:     
 2247:     return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
 2248: }
 2249: 
 2250: 1;
 2251: 
 2252: package Apache::lonnavmaps::iterator;
 2253: 
 2254: =pod
 2255: 
 2256: =back
 2257: 
 2258: =head1 Object: navmap Iterator
 2259: 
 2260: An I<iterator> encapsulates the logic required to traverse a data
 2261: structure. navmap uses an iterator to traverse the course map
 2262: according to the criteria you wish to use.
 2263: 
 2264: To obtain an iterator, call the B<getIterator>() function of a
 2265: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
 2266: directly.) This will return a reference to the iterator:
 2267: 
 2268: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 2269: 
 2270: To get the next thing from the iterator, call B<next>:
 2271: 
 2272: C<my $nextThing = $resourceIterator-E<gt>next()>
 2273: 
 2274: getIterator behaves as follows:
 2275: 
 2276: =over 4
 2277: 
 2278: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
 2279: 
 2280: All parameters are optional. firstResource is a resource reference
 2281: corresponding to where the iterator should start. It defaults to
 2282: navmap->firstResource() for the corresponding nav map. finishResource
 2283: corresponds to where you want the iterator to end, defaulting to
 2284: navmap->finishResource(). filterHash is a hash used as a set
 2285: containing strings representing the resource IDs, defaulting to
 2286: empty. Condition is a 1 or 0 that sets what to do with the filter
 2287: hash: If a 0, then only resources that exist IN the filterHash will be
 2288: recursed on. If it is a 1, only resources NOT in the filterHash will
 2289: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
 2290: false (default), the iterator will only return the first level of map
 2291: that is not just a single, 'redirecting' map. If true, the iterator
 2292: will return all information, starting with the top-level map,
 2293: regardless of content. returnTopMap, if true (default false), will
 2294: cause the iterator to return the top-level map object (resource 0.0)
 2295: before anything else.
 2296: 
 2297: Thus, by default, only top-level resources will be shown. Change the
 2298: condition to a 1 without changing the hash, and all resources will be
 2299: shown. Changing the condition to 1 and including some values in the
 2300: hash will allow you to selectively suppress parts of the navmap, while
 2301: leaving it on 0 and adding things to the hash will allow you to
 2302: selectively add parts of the nav map. See the handler code for
 2303: examples.
 2304: 
 2305: The iterator will return either a reference to a resource object, or a
 2306: token representing something in the map, such as the beginning of a
 2307: new branch. The possible tokens are:
 2308: 
 2309: =over 4
 2310: 
 2311: =item * B<END_ITERATOR>:
 2312: 
 2313: The iterator has returned all that it's going to. Further calls to the
 2314: iterator will just produce more of these. This is a "false" value, and
 2315: is the only false value the iterator which will be returned, so it can
 2316: be used as a loop sentinel.
 2317: 
 2318: =item * B<BEGIN_MAP>:
 2319: 
 2320: A new map is being recursed into. This is returned I<after> the map
 2321: resource itself is returned.
 2322: 
 2323: =item * B<END_MAP>:
 2324: 
 2325: The map is now done.
 2326: 
 2327: =item * B<BEGIN_BRANCH>:
 2328: 
 2329: A branch is now starting. The next resource returned will be the first
 2330: in that branch.
 2331: 
 2332: =item * B<END_BRANCH>:
 2333: 
 2334: The branch is now done.
 2335: 
 2336: =back
 2337: 
 2338: The tokens are retreivable via methods on the iterator object, i.e.,
 2339: $iterator->END_MAP.
 2340: 
 2341: Maps can contain empty resources. The iterator will automatically skip
 2342: over such resources, but will still treat the structure
 2343: correctly. Thus, a complicated map with several branches, but
 2344: consisting entirely of empty resources except for one beginning or
 2345: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
 2346: but only one resource will be returned.
 2347: 
 2348: =head2 Normal Usage
 2349: 
 2350: Normal usage of the iterator object is to do the following:
 2351: 
 2352:  my $it = $navmap->getIterator([your params here]);
 2353:  my $curRes;
 2354:  while ($curRes = $it->next()) {
 2355:    [your logic here]
 2356:  }
 2357: 
 2358: Note that inside of the loop, it's frequently useful to check if
 2359: "$curRes" is a reference or not with the reference function; only
 2360: resource objects will be references, and any non-references will 
 2361: be the tokens described above.
 2362: 
 2363: Also note there is some old code floating around that trys to track
 2364: the depth of the iterator to see when it's done; do not copy that 
 2365: code. It is difficult to get right and harder to understand then
 2366: this. They should be migrated to this new style.
 2367: 
 2368: =back
 2369: 
 2370: =cut
 2371: 
 2372: # Here are the tokens for the iterator:
 2373: 
 2374: sub END_ITERATOR { return 0; }
 2375: sub BEGIN_MAP { return 1; }    # begining of a new map
 2376: sub END_MAP { return 2; }      # end of the map
 2377: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 2378: sub END_BRANCH { return 4; }   # end of a branch
 2379: sub FORWARD { return 1; }      # go forward
 2380: sub BACKWARD { return 2; }
 2381: 
 2382: sub min {
 2383:     (my $a, my $b) = @_;
 2384:     if ($a < $b) { return $a; } else { return $b; }
 2385: }
 2386: 
 2387: sub new {
 2388:     # magic invocation to create a class instance
 2389:     my $proto = shift;
 2390:     my $class = ref($proto) || $proto;
 2391:     my $self = {};
 2392: 
 2393:     $self->{NAV_MAP} = shift;
 2394:     return undef unless ($self->{NAV_MAP});
 2395: 
 2396:     # Handle the parameters
 2397:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 2398:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 2399: 
 2400:     # If the given resources are just the ID of the resource, get the
 2401:     # objects
 2402:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 2403:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 2404:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 2405:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 2406: 
 2407:     $self->{FILTER} = shift;
 2408: 
 2409:     # A hash, used as a set, of resource already seen
 2410:     $self->{ALREADY_SEEN} = shift;
 2411:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 2412:     $self->{CONDITION} = shift;
 2413: 
 2414:     # Do we want to automatically follow "redirection" maps?
 2415:     $self->{FORCE_TOP} = shift;
 2416: 
 2417:     # Do we want to return the top-level map object (resource 0.0)?
 2418:     $self->{RETURN_0} = shift;
 2419:     # have we done that yet?
 2420:     $self->{HAVE_RETURNED_0} = 0;
 2421: 
 2422:     # Now, we need to pre-process the map, by walking forward and backward
 2423:     # over the parts of the map we're going to look at.
 2424: 
 2425:     # The processing steps are exactly the same, except for a few small 
 2426:     # changes, so I bundle those up in the following list of two elements:
 2427:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
 2428:     # first_resource).
 2429:     # This prevents writing nearly-identical code twice.
 2430:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
 2431:                         'FIRST_RESOURCE'],
 2432:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
 2433:                         'FINISH_RESOURCE'] );
 2434: 
 2435:     my $maxDepth = 0; # tracks max depth
 2436: 
 2437:     # If there is only one resource in this map, and it's a map, we
 2438:     # want to remember that, so the user can ask for the first map
 2439:     # that isn't just a redirector.
 2440:     my $resource; my $resourceCount = 0;
 2441: 
 2442:     # Documentation on this algorithm can be found in the CVS repository at 
 2443:     # /docs/lonnavdocs; these "**#**" markers correspond to documentation
 2444:     # in that file.
 2445:     # **1**
 2446: 
 2447:     foreach my $pass (@iterations) {
 2448:         my $direction = $pass->[0];
 2449:         my $valName = $pass->[1];
 2450:         my $nextResourceMethod = $pass->[2];
 2451:         my $firstResourceName = $pass->[3];
 2452: 
 2453:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
 2454:                                                             $self->{FIRST_RESOURCE},
 2455:                                                             $self->{FINISH_RESOURCE},
 2456:                                                             {}, undef, 0, $direction);
 2457:     
 2458:         # prime the recursion
 2459:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
 2460: 	$iterator->next();
 2461:         my $curRes = $iterator->next();
 2462: 	my $depth = 1;
 2463:         while ($depth > 0) {
 2464: 	    if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
 2465: 	    if ($curRes == $iterator->END_MAP()) { $depth--; }
 2466: 
 2467:             if (ref($curRes)) {
 2468:                 # If there's only one resource, this will save it
 2469:                 # we have to filter empty resources from consideration here,
 2470:                 # or even "empty", redirecting maps have two (start & finish)
 2471:                 # or three (start, finish, plus redirector)
 2472:                 if($direction == FORWARD && $curRes->src()) { 
 2473:                     $resource = $curRes; $resourceCount++; 
 2474:                 }
 2475:                 my $resultingVal = $curRes->{DATA}->{$valName};
 2476:                 my $nextResources = $curRes->$nextResourceMethod();
 2477:                 my $nextCount = scalar(@{$nextResources});
 2478: 
 2479:                 if ($nextCount == 1) { # **3**
 2480:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
 2481:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
 2482:                 }
 2483:                 
 2484:                 if ($nextCount > 1) { # **4**
 2485:                     foreach my $res (@{$nextResources}) {
 2486:                         my $current = $res->{DATA}->{$valName} || 999999999;
 2487:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
 2488:                     }
 2489:                 }
 2490:             }
 2491:             
 2492:             # Assign the final val (**2**)
 2493:             if (ref($curRes) && $direction == BACKWARD()) {
 2494:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
 2495:                                      $curRes->{DATA}->{BOT_UP_VAL});
 2496:                 
 2497:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
 2498:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
 2499:             }
 2500: 
 2501: 	    $curRes = $iterator->next();
 2502:         }
 2503:     }
 2504: 
 2505:     # Check: Was this only one resource, a map?
 2506:     if ($resourceCount == 1 && $resource->is_map() && !$self->{FORCE_TOP}) { 
 2507:         my $firstResource = $resource->map_start();
 2508:         my $finishResource = $resource->map_finish();
 2509:         return 
 2510:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 2511:                                               $finishResource, $self->{FILTER},
 2512:                                               $self->{ALREADY_SEEN}, 
 2513:                                               $self->{CONDITION}, 0);
 2514:         
 2515:     }
 2516: 
 2517:     # Set up some bookkeeping information.
 2518:     $self->{CURRENT_DEPTH} = 0;
 2519:     $self->{MAX_DEPTH} = $maxDepth;
 2520:     $self->{STACK} = [];
 2521:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2522:     $self->{FINISHED} = 0; # When true, the iterator has finished
 2523: 
 2524:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
 2525:         push @{$self->{STACK}}, [];
 2526:     }
 2527: 
 2528:     # Prime the recursion w/ the first resource **5**
 2529:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
 2530:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
 2531: 
 2532:     bless ($self);
 2533: 
 2534:     return $self;
 2535: }
 2536: 
 2537: sub next {
 2538:     my $self = shift;
 2539: 
 2540:     if ($self->{FINISHED}) {
 2541: 	return END_ITERATOR();
 2542:     }
 2543: 
 2544:     # If we want to return the top-level map object, and haven't yet,
 2545:     # do so.
 2546:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
 2547:         $self->{HAVE_RETURNED_0} = 1;
 2548:         return $self->{NAV_MAP}->getById('0.0');
 2549:     }
 2550: 
 2551:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2552:         # grab the next from the recursive iterator 
 2553:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 2554: 
 2555:         # is it a begin or end map? If so, update the depth
 2556:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 2557:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 2558: 
 2559:         # Are we back at depth 0? If so, stop recursing
 2560:         if ($self->{RECURSIVE_DEPTH} == 0) {
 2561:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2562:         }
 2563: 
 2564:         return $next;
 2565:     }
 2566: 
 2567:     if (defined($self->{FORCE_NEXT})) {
 2568:         my $tmp = $self->{FORCE_NEXT};
 2569:         $self->{FORCE_NEXT} = undef;
 2570:         return $tmp;
 2571:     }
 2572: 
 2573:     # Have we not yet begun? If not, return BEGIN_MAP and
 2574:     # remember we've started.
 2575:     if ( !$self->{STARTED} ) { 
 2576:         $self->{STARTED} = 1;
 2577:         return $self->BEGIN_MAP();
 2578:     }
 2579: 
 2580:     # Here's the guts of the iterator.
 2581:     
 2582:     # Find the next resource, if any.
 2583:     my $found = 0;
 2584:     my $i = $self->{MAX_DEPTH};
 2585:     my $newDepth;
 2586:     my $here;
 2587:     while ( $i >= 0 && !$found ) {
 2588:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
 2589:             $here = pop @{$self->{STACK}->[$i]}; # **7**
 2590:             $found = 1;
 2591:             $newDepth = $i;
 2592:         }
 2593:         $i--;
 2594:     }
 2595: 
 2596:     # If we still didn't find anything, we're done.
 2597:     if ( !$found ) {
 2598:         # We need to get back down to the correct branch depth
 2599:         if ( $self->{CURRENT_DEPTH} > 0 ) {
 2600:             $self->{CURRENT_DEPTH}--;
 2601:             return END_BRANCH();
 2602:         } else {
 2603: 	    $self->{FINISHED} = 1;
 2604:             return END_MAP();
 2605:         }
 2606:     }
 2607: 
 2608:     # If this is not a resource, it must be an END_BRANCH marker we want
 2609:     # to return directly.
 2610:     if (!ref($here)) { # **8**
 2611:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
 2612:             $self->{CURRENT_DEPTH}--;
 2613:             return $here;
 2614:         }
 2615:     }
 2616: 
 2617:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
 2618:     $self->{HERE} = $here;
 2619: 
 2620:     # Get to the right level
 2621:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
 2622:         push @{$self->{STACK}->[$newDepth]}, $here;
 2623:         $self->{CURRENT_DEPTH}--;
 2624:         return END_BRANCH();
 2625:     }
 2626:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
 2627:         push @{$self->{STACK}->[$newDepth]}, $here;
 2628:         $self->{CURRENT_DEPTH}++;
 2629:         return BEGIN_BRANCH();
 2630:     }
 2631: 
 2632:     # If we made it here, we have the next resource, and we're at the
 2633:     # right branch level. So let's examine the resource for where
 2634:     # we can get to from here.
 2635: 
 2636:     # So we need to look at all the resources we can get to from here,
 2637:     # categorize them if we haven't seen them, remember if we have a new
 2638:     my $nextUnfiltered = $here->getNext();
 2639:     my $maxDepthAdded = -1;
 2640:     
 2641:     for (@$nextUnfiltered) {
 2642:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 2643:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
 2644:             push @{$self->{STACK}->[$depth]}, $_;
 2645:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
 2646:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
 2647:         }
 2648:     }
 2649: 
 2650:     # Is this the end of a branch? If so, all of the resources examined above
 2651:     # led to lower levels then the one we are currently at, so we push a END_BRANCH
 2652:     # marker onto the stack so we don't forget.
 2653:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
 2654:     # BC branch and gets to C, it will see F as the only next resource, but it's
 2655:     # one level lower. Thus, this is the end of the branch, since there are no
 2656:     # more resources added to this level or above.
 2657:     # We don't do this if the examined resource is the finish resource,
 2658:     # because the condition given above is true, but the "END_MAP" will
 2659:     # take care of things and we should already be at depth 0.
 2660:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
 2661:     if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
 2662:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
 2663:     }
 2664: 
 2665:     # That ends the main iterator logic. Now, do we want to recurse
 2666:     # down this map (if this resource is a map)?
 2667:     if ($self->{HERE}->is_map() &&
 2668:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
 2669:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 2670:         my $firstResource = $self->{HERE}->map_start();
 2671:         my $finishResource = $self->{HERE}->map_finish();
 2672: 
 2673:         $self->{RECURSIVE_ITERATOR} = 
 2674:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 2675:                                               $finishResource, $self->{FILTER},
 2676:                                               $self->{ALREADY_SEEN}, $self->{CONDITION});
 2677:     }
 2678: 
 2679:     # If this is a blank resource, don't actually return it.
 2680:     # Should you ever find you need it, make sure to add an option to the code
 2681:     #  that you can use; other things depend on this behavior.
 2682:     my $browsePriv = $self->{HERE}->browsePriv();
 2683:     if (!$self->{HERE}->src() || 
 2684:         (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
 2685:         return $self->next();
 2686:     }
 2687: 
 2688:     return $self->{HERE};
 2689: 
 2690: }
 2691: 
 2692: =pod
 2693: 
 2694: The other method available on the iterator is B<getStack>, which
 2695: returns an array populated with the current 'stack' of maps, as
 2696: references to the resource objects. Example: This is useful when
 2697: making the navigation map, as we need to check whether we are under a
 2698: page map to see if we need to link directly to the resource, or to the
 2699: page. The first elements in the array will correspond to the top of
 2700: the stack (most inclusive map).
 2701: 
 2702: =cut
 2703: 
 2704: sub getStack {
 2705:     my $self=shift;
 2706: 
 2707:     my @stack;
 2708: 
 2709:     $self->populateStack(\@stack);
 2710: 
 2711:     return \@stack;
 2712: }
 2713: 
 2714: # Private method: Calls the iterators recursively to populate the stack.
 2715: sub populateStack {
 2716:     my $self=shift;
 2717:     my $stack = shift;
 2718: 
 2719:     push @$stack, $self->{HERE} if ($self->{HERE});
 2720: 
 2721:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2722:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 2723:     }
 2724: }
 2725: 
 2726: 1;
 2727: 
 2728: package Apache::lonnavmaps::DFSiterator;
 2729: 
 2730: # Not documented in the perldoc: This is a simple iterator that just walks
 2731: #  through the nav map and presents the resources in a depth-first search
 2732: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
 2733: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
 2734: #  useful for pre-processing of some kind, and is in fact used by the main
 2735: #  iterator that way, but that's about it.
 2736: # One could imagine merging this into the init routine of the main iterator,
 2737: #  but this might as well be left seperate, since it is possible some other
 2738: #  use might be found for it. - Jeremy
 2739: 
 2740: # Unlike the main iterator, this DOES return all resources, even blank ones.
 2741: #  The main iterator needs them to correctly preprocess the map.
 2742: 
 2743: sub BEGIN_MAP { return 1; }    # begining of a new map
 2744: sub END_MAP { return 2; }      # end of the map
 2745: sub FORWARD { return 1; }      # go forward
 2746: sub BACKWARD { return 2; }
 2747: 
 2748: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
 2749: #         filter hash ref (or undef), already seen hash or undef, condition
 2750: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
 2751: sub new {
 2752:     # magic invocation to create a class instance
 2753:     my $proto = shift;
 2754:     my $class = ref($proto) || $proto;
 2755:     my $self = {};
 2756: 
 2757:     $self->{NAV_MAP} = shift;
 2758:     return undef unless ($self->{NAV_MAP});
 2759: 
 2760:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 2761:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 2762: 
 2763:     # If the given resources are just the ID of the resource, get the
 2764:     # objects
 2765:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 2766:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 2767:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 2768:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 2769: 
 2770:     $self->{FILTER} = shift;
 2771: 
 2772:     # A hash, used as a set, of resource already seen
 2773:     $self->{ALREADY_SEEN} = shift;
 2774:      if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 2775:     $self->{CONDITION} = shift;
 2776:     $self->{DIRECTION} = shift || FORWARD();
 2777: 
 2778:     # Flag: Have we started yet?
 2779:     $self->{STARTED} = 0;
 2780: 
 2781:     # Should we continue calling the recursive iterator, if any?
 2782:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2783:     # The recursive iterator, if any
 2784:     $self->{RECURSIVE_ITERATOR} = undef;
 2785:     # Are we recursing on a map, or a branch?
 2786:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 2787:     # And the count of how deep it is, so that this iterator can keep track of
 2788:     # when to pick back up again.
 2789:     $self->{RECURSIVE_DEPTH} = 0;
 2790: 
 2791:     # For keeping track of our branches, we maintain our own stack
 2792:     $self->{STACK} = [];
 2793: 
 2794:     # Start with the first resource
 2795:     if ($self->{DIRECTION} == FORWARD) {
 2796:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
 2797:     } else {
 2798:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
 2799:     }
 2800: 
 2801:     bless($self);
 2802:     return $self;
 2803: }
 2804: 
 2805: sub next {
 2806:     my $self = shift;
 2807:     
 2808:     # Are we using a recursive iterator? If so, pull from that and
 2809:     # watch the depth; we want to resume our level at the correct time.
 2810:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2811:         # grab the next from the recursive iterator
 2812:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 2813:         
 2814:         # is it a begin or end map? Update depth if so
 2815:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 2816:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 2817: 
 2818:         # Are we back at depth 0? If so, stop recursing.
 2819:         if ($self->{RECURSIVE_DEPTH} == 0) {
 2820:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 2821:         }
 2822:         
 2823:         return $next;
 2824:     }
 2825: 
 2826:     # Is there a current resource to grab? If not, then return
 2827:     # END_MAP, which will end the iterator.
 2828:     if (scalar(@{$self->{STACK}}) == 0) {
 2829:         return $self->END_MAP();
 2830:     }
 2831: 
 2832:     # Have we not yet begun? If not, return BEGIN_MAP and 
 2833:     # remember that we've started.
 2834:     if ( !$self->{STARTED} ) {
 2835:         $self->{STARTED} = 1;
 2836:         return $self->BEGIN_MAP;
 2837:     }
 2838: 
 2839:     # Get the next resource in the branch
 2840:     $self->{HERE} = pop @{$self->{STACK}};
 2841: 
 2842:     # remember that we've seen this, so we don't return it again later
 2843:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 2844:     
 2845:     # Get the next possible resources
 2846:     my $nextUnfiltered;
 2847:     if ($self->{DIRECTION} == FORWARD()) {
 2848:         $nextUnfiltered = $self->{HERE}->getNext();
 2849:     } else {
 2850:         $nextUnfiltered = $self->{HERE}->getPrevious();
 2851:     }
 2852:     my $next = [];
 2853: 
 2854:     # filter the next possibilities to remove things we've 
 2855:     # already seen.
 2856:     foreach (@$nextUnfiltered) {
 2857:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 2858:             push @$next, $_;
 2859:         }
 2860:     }
 2861: 
 2862:     while (@$next) {
 2863:         # copy the next possibilities over to the stack
 2864:         push @{$self->{STACK}}, shift @$next;
 2865:     }
 2866: 
 2867:     # If this is a map and we want to recurse down it... (not filtered out)
 2868:     if ($self->{HERE}->is_map() && 
 2869:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 2870:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 2871:         my $firstResource = $self->{HERE}->map_start();
 2872:         my $finishResource = $self->{HERE}->map_finish();
 2873: 
 2874:         $self->{RECURSIVE_ITERATOR} =
 2875:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
 2876:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 2877:                                              $self->{CONDITION}, $self->{DIRECTION});
 2878:     }
 2879: 
 2880:     return $self->{HERE};
 2881: }
 2882: 
 2883: # Identical to the full iterator methods of the same name. Hate to copy/paste
 2884: # but I also hate to "inherit" either iterator from the other.
 2885: 
 2886: sub getStack {
 2887:     my $self=shift;
 2888: 
 2889:     my @stack;
 2890: 
 2891:     $self->populateStack(\@stack);
 2892: 
 2893:     return \@stack;
 2894: }
 2895: 
 2896: # Private method: Calls the iterators recursively to populate the stack.
 2897: sub populateStack {
 2898:     my $self=shift;
 2899:     my $stack = shift;
 2900: 
 2901:     push @$stack, $self->{HERE} if ($self->{HERE});
 2902: 
 2903:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 2904:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 2905:     }
 2906: }
 2907: 
 2908: 1;
 2909: 
 2910: package Apache::lonnavmaps::resource;
 2911: 
 2912: use Apache::lonnet;
 2913: 
 2914: =pod
 2915: 
 2916: =head1 Object: resource 
 2917: 
 2918: X<resource, navmap object>
 2919: A resource object encapsulates a resource in a resource map, allowing
 2920: easy manipulation of the resource, querying the properties of the
 2921: resource (including user properties), and represents a reference that
 2922: can be used as the canonical representation of the resource by
 2923: lonnavmap clients like renderers.
 2924: 
 2925: A resource only makes sense in the context of a navmap, as some of the
 2926: data is stored in the navmap object.
 2927: 
 2928: You will probably never need to instantiate this object directly. Use
 2929: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
 2930: starting resource.
 2931: 
 2932: Resource objects respect the parameter_hiddenparts, which suppresses 
 2933: various parts according to the wishes of the map author. As of this
 2934: writing, there is no way to override this parameter, and suppressed
 2935: parts will never be returned, nor will their response types or ids be
 2936: stored.
 2937: 
 2938: =head2 Overview
 2939: 
 2940: A B<Resource> is the most granular type of object in LON-CAPA that can
 2941: be included in a course. It can either be a particular resource, like
 2942: an HTML page, external resource, problem, etc., or it can be a
 2943: container sequence, such as a "page" or a "map".
 2944: 
 2945: To see a sequence from the user's point of view, please see the
 2946: B<Creating a Course: Maps and Sequences> chapter of the Author's
 2947: Manual.
 2948: 
 2949: A Resource Object, once obtained from a navmap object via a B<getBy*>
 2950: method of the navmap, or from an iterator, allows you to query
 2951: information about that resource.
 2952: 
 2953: Generally, you do not ever want to create a resource object yourself,
 2954: so creation has been left undocumented. Always retrieve resources
 2955: from navmap objects.
 2956: 
 2957: =head3 Identifying Resources
 2958: 
 2959: X<big hash>Every resource is identified by a Resource ID in the big hash that is
 2960: unique to that resource for a given course. X<resource ID, in big hash>
 2961: The Resource ID has the form #.#, where the first number is the same
 2962: for every resource in a map, and the second is unique. For instance,
 2963: for a course laid out like this:
 2964: 
 2965:  * Problem 1
 2966:  * Map
 2967:    * Resource 2
 2968:    * Resource 3
 2969: 
 2970: C<Problem 1> and C<Map> will share a first number, and C<Resource 2>
 2971: C<Resource 3> will share a first number. The second number may end up
 2972: re-used between the two groups.
 2973: 
 2974: The resource ID is only used in the big hash, but can be used in the
 2975: context of a course to identify a resource easily. (For instance, the
 2976: printing system uses it to record which resources from a sequence you 
 2977: wish to print.)
 2978: 
 2979: X<symb> X<resource, symb>
 2980: All resources also have B<symb>s, which uniquely identify a resource
 2981: in a course. Many internal LON-CAPA functions expect a symb. A symb
 2982: carries along with it the URL of the resource, and the map it appears
 2983: in. Symbs are much larger then resource IDs.
 2984: 
 2985: =cut
 2986: 
 2987: sub new {
 2988:     # magic invocation to create a class instance
 2989:     my $proto = shift;
 2990:     my $class = ref($proto) || $proto;
 2991:     my $self = {};
 2992: 
 2993:     $self->{NAV_MAP} = shift;
 2994:     $self->{ID} = shift;
 2995: 
 2996:     # Store this new resource in the parent nav map's cache.
 2997:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 2998:     $self->{RESOURCE_ERROR} = 0;
 2999: 
 3000:     # A hash that can be used by two-pass algorithms to store data
 3001:     # about this resource in. Not used by the resource object
 3002:     # directly.
 3003:     $self->{DATA} = {};
 3004:    
 3005:     bless($self);
 3006:     
 3007:     return $self;
 3008: }
 3009: 
 3010: # private function: simplify the NAV_HASH lookups we keep doing
 3011: # pass the name, and to automatically append my ID, pass a true val on the
 3012: # second param
 3013: sub navHash {
 3014:     my $self = shift;
 3015:     my $param = shift;
 3016:     my $id = shift;
 3017:     return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
 3018: }
 3019: 
 3020: =pod
 3021: 
 3022: =head2 Methods
 3023: 
 3024: Once you have a resource object, here's what you can do with it:
 3025: 
 3026: =head3 Attribute Retrieval
 3027: 
 3028: Every resource has certain attributes that can be retrieved and used:
 3029: 
 3030: =over 4
 3031: 
 3032: =item * B<ID>: Every resource has an ID that is unique for that
 3033:     resource in the course it is in. The ID is actually in the hash
 3034:     representing the resource, so for a resource object $res, obtain
 3035:     it via C<$res->{ID}).
 3036: 
 3037: =item * B<compTitle>:
 3038: 
 3039: Returns a "composite title", that is equal to $res->title() if the
 3040: resource has a title, and is otherwise the last part of the URL (e.g.,
 3041: "problem.problem").
 3042: 
 3043: =item * B<ext>:
 3044: 
 3045: Returns true if the resource is external.
 3046: 
 3047: =item * B<kind>:
 3048: 
 3049: Returns the kind of the resource from the compiled nav map.
 3050: 
 3051: =item * B<randomout>:
 3052: 
 3053: Returns true if this resource was chosen to NOT be shown to the user
 3054: by the random map selection feature. In other words, this is usually
 3055: false.
 3056: 
 3057: =item * B<randompick>:
 3058: 
 3059: Returns true for a map if the randompick feature is being used on the
 3060: map. (?)
 3061: 
 3062: =item * B<src>:
 3063: 
 3064: Returns the source for the resource.
 3065: 
 3066: =item * B<symb>:
 3067: 
 3068: Returns the symb for the resource.
 3069: 
 3070: =item * B<title>:
 3071: 
 3072: Returns the title of the resource.
 3073: 
 3074: =back
 3075: 
 3076: =cut
 3077: 
 3078: # These info functions can be used directly, as they don't return
 3079: # resource information.
 3080: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
 3081: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
 3082: sub from { my $self=shift; return $self->navHash("from_", 1); }
 3083: # considered private and undocumented
 3084: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 3085: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 3086: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
 3087: sub randompick { 
 3088:     my $self = shift;
 3089:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
 3090:                                                '.0.parameter_randompick'};
 3091: }
 3092: sub src { 
 3093:     my $self=shift;
 3094:     return $self->navHash("src_", 1);
 3095: }
 3096: sub symb {
 3097:     my $self=shift;
 3098:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 3099:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 3100:     my $symb = &Apache::lonnet::declutter($self->navHash('map_id_'.$first)) 
 3101:         . '___' . $second . '___' . $symbSrc;
 3102:     return &Apache::lonnet::symbclean($symb);
 3103: }
 3104: sub title { 
 3105:     my $self=shift; 
 3106:     if ($self->{ID} eq '0.0') {
 3107: 	# If this is the top-level map, return the title of the course
 3108: 	# since this map can not be titled otherwise.
 3109: 	return $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 3110:     }
 3111:     return $self->navHash("title_", 1); }
 3112: # considered private and undocumented
 3113: sub to { my $self=shift; return $self->navHash("to_", 1); }
 3114: sub compTitle {
 3115:     my $self = shift;
 3116:     my $title = $self->title();
 3117:     $title=~s/\&colon\;/\:/gs;
 3118:     if (!$title) {
 3119:         $title = $self->src();
 3120:         $title = substr($title, rindex($title, '/') + 1);
 3121:     }
 3122:     return $title;
 3123: }
 3124: =pod
 3125: 
 3126: B<Predicate Testing the Resource>
 3127: 
 3128: These methods are shortcuts to deciding if a given resource has a given property.
 3129: 
 3130: =over 4
 3131: 
 3132: =item * B<is_map>:
 3133: 
 3134: Returns true if the resource is a map type.
 3135: 
 3136: =item * B<is_problem>:
 3137: 
 3138: Returns true if the resource is a problem type, false
 3139: otherwise. (Looks at the extension on the src field; might need more
 3140: to work correctly.)
 3141: 
 3142: =item * B<is_page>:
 3143: 
 3144: Returns true if the resource is a page.
 3145: 
 3146: =item * B<is_sequence>:
 3147: 
 3148: Returns true if the resource is a sequence.
 3149: 
 3150: =back
 3151: 
 3152: =cut
 3153: 
 3154: 
 3155: sub is_html {
 3156:     my $self=shift;
 3157:     my $src = $self->src();
 3158:     return ($src =~ /html$/);
 3159: }
 3160: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 3161: sub is_page {
 3162:     my $self=shift;
 3163:     my $src = $self->src();
 3164:     return $self->navHash("is_map_", 1) && 
 3165: 	$self->navHash("map_type_" . $self->map_pc()) eq 'page';
 3166: }
 3167: sub is_problem {
 3168:     my $self=shift;
 3169:     my $src = $self->src();
 3170:     return ($src =~ /problem$/);
 3171: }
 3172: sub is_sequence {
 3173:     my $self=shift;
 3174:     my $src = $self->src();
 3175:     return $self->navHash("is_map_", 1) && 
 3176: 	$self->navHash("map_type_" . $self->map_pc()) eq 'sequence';
 3177: }
 3178: 
 3179: # Private method: Shells out to the parmval in the nav map, handler parts.
 3180: sub parmval {
 3181:     my $self = shift;
 3182:     my $what = shift;
 3183:     my $part = shift;
 3184:     if (!defined($part)) { 
 3185:         $part = '0'; 
 3186:     }
 3187:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
 3188: }
 3189: 
 3190: =pod
 3191: 
 3192: B<Map Methods>
 3193: 
 3194: These methods are useful for getting information about the map
 3195: properties of the resource, if the resource is a map (B<is_map>).
 3196: 
 3197: =over 4
 3198: 
 3199: =item * B<map_finish>:
 3200: 
 3201: Returns a reference to a resource object corresponding to the finish
 3202: resource of the map.
 3203: 
 3204: =item * B<map_pc>:
 3205: 
 3206: Returns the pc value of the map, which is the first number that
 3207: appears in the resource ID of the resources in the map, and is the
 3208: number that appears around the middle of the symbs of the resources in
 3209: that map.
 3210: 
 3211: =item * B<map_start>:
 3212: 
 3213: Returns a reference to a resource object corresponding to the start
 3214: resource of the map.
 3215: 
 3216: =item * B<map_type>:
 3217: 
 3218: Returns a string with the type of the map in it.
 3219: 
 3220: =back
 3221: 
 3222: =cut
 3223: 
 3224: sub map_finish {
 3225:     my $self = shift;
 3226:     my $src = $self->src();
 3227:     $src = Apache::lonnet::clutter($src);
 3228:     my $res = $self->navHash("map_finish_$src", 0);
 3229:     $res = $self->{NAV_MAP}->getById($res);
 3230:     return $res;
 3231: }
 3232: sub map_pc {
 3233:     my $self = shift;
 3234:     my $src = $self->src();
 3235:     return $self->navHash("map_pc_$src", 0);
 3236: }
 3237: sub map_start {
 3238:     my $self = shift;
 3239:     my $src = $self->src();
 3240:     $src = Apache::lonnet::clutter($src);
 3241:     my $res = $self->navHash("map_start_$src", 0);
 3242:     $res = $self->{NAV_MAP}->getById($res);
 3243:     return $res;
 3244: }
 3245: sub map_type {
 3246:     my $self = shift;
 3247:     my $pc = $self->map_pc();
 3248:     return $self->navHash("map_type_$pc", 0);
 3249: }
 3250: 
 3251: #####
 3252: # Property queries
 3253: #####
 3254: 
 3255: # These functions will be responsible for returning the CORRECT
 3256: # VALUE for the parameter, no matter what. So while they may look
 3257: # like direct calls to parmval, they can be more then that.
 3258: # So, for instance, the duedate function should use the "duedatetype"
 3259: # information, rather then the resource object user.
 3260: 
 3261: =pod
 3262: 
 3263: =head2 Resource Parameters
 3264: 
 3265: In order to use the resource parameters correctly, the nav map must
 3266: have been instantiated with genCourseAndUserOptions set to true, so
 3267: the courseopt and useropt is read correctly. Then, you can call these
 3268: functions to get the relevant parameters for the resource. Each
 3269: function defaults to part "0", but can be directed to another part by
 3270: passing the part as the parameter.
 3271: 
 3272: These methods are responsible for getting the parameter correct, not
 3273: merely reflecting the contents of the GDBM hashes. As we move towards
 3274: dates relative to other dates, these methods should be updated to
 3275: reflect that. (Then, anybody using these methods will not have to update
 3276: their code.)
 3277: 
 3278: =over 4
 3279: 
 3280: =item * B<acc>:
 3281: 
 3282: Get the Client IP/Name Access Control information.
 3283: 
 3284: =item * B<answerdate>:
 3285: 
 3286: Get the answer-reveal date for the problem.
 3287: 
 3288: =item * B<awarded>: 
 3289: 
 3290: Gets the awarded value for the problem part. Requires genUserData set to
 3291: true when the navmap object was created.
 3292: 
 3293: =item * B<duedate>:
 3294: 
 3295: Get the due date for the problem.
 3296: 
 3297: =item * B<tries>:
 3298: 
 3299: Get the number of tries the student has used on the problem.
 3300: 
 3301: =item * B<maxtries>:
 3302: 
 3303: Get the number of max tries allowed.
 3304: 
 3305: =item * B<opendate>:
 3306: 
 3307: Get the open date for the problem.
 3308: 
 3309: =item * B<sig>:
 3310: 
 3311: Get the significant figures setting.
 3312: 
 3313: =item * B<tol>:
 3314: 
 3315: Get the tolerance for the problem.
 3316: 
 3317: =item * B<tries>:
 3318: 
 3319: Get the number of tries the user has already used on the problem.
 3320: 
 3321: =item * B<type>:
 3322: 
 3323: Get the question type for the problem.
 3324: 
 3325: =item * B<weight>:
 3326: 
 3327: Get the weight for the problem.
 3328: 
 3329: =back
 3330: 
 3331: =cut
 3332: 
 3333: sub acc {
 3334:     (my $self, my $part) = @_;
 3335:     return $self->parmval("acc", $part);
 3336: }
 3337: sub answerdate {
 3338:     (my $self, my $part) = @_;
 3339:     # Handle intervals
 3340:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
 3341:         return $self->duedate($part) + 
 3342:             $self->parmval("answerdate", $part);
 3343:     }
 3344:     return $self->parmval("answerdate", $part);
 3345: }
 3346: sub awarded { 
 3347:     my $self = shift; my $part = shift;
 3348:     $self->{NAV_MAP}->get_user_data();
 3349:     if (!defined($part)) { $part = '0'; }
 3350:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->symb()}->{'resource.'.$part.'.awarded'};
 3351: }
 3352: sub duedate {
 3353:     (my $self, my $part) = @_;
 3354:     return $self->parmval("duedate", $part);
 3355: }
 3356: sub maxtries {
 3357:     (my $self, my $part) = @_;
 3358:     return $self->parmval("maxtries", $part);
 3359: }
 3360: sub opendate {
 3361:     (my $self, my $part) = @_;
 3362:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
 3363:         return $self->duedate($part) -
 3364:             $self->parmval("opendate", $part);
 3365:     }
 3366:     return $self->parmval("opendate");
 3367: }
 3368: sub problemstatus {
 3369:     (my $self, my $part) = @_;
 3370:     return lc $self->parmval("problemstatus", $part);
 3371: }
 3372: sub sig {
 3373:     (my $self, my $part) = @_;
 3374:     return $self->parmval("sig", $part);
 3375: }
 3376: sub tol {
 3377:     (my $self, my $part) = @_;
 3378:     return $self->parmval("tol", $part);
 3379: }
 3380: sub tries { 
 3381:     my $self = shift; 
 3382:     my $tries = $self->queryRestoreHash('tries', shift);
 3383:     if (!defined($tries)) { return '0';}
 3384:     return $tries;
 3385: }
 3386: sub type {
 3387:     (my $self, my $part) = @_;
 3388:     return $self->parmval("type", $part);
 3389: }
 3390: sub weight { 
 3391:     my $self = shift; my $part = shift;
 3392:     if (!defined($part)) { $part = '0'; }
 3393:     return &Apache::lonnet::EXT('resource.'.$part.'.weight',
 3394: 				$self->symb(), $ENV{'user.domain'},
 3395: 				$ENV{'user.name'}, 
 3396: 				$ENV{'request.course.sec'});
 3397: 
 3398: }
 3399: 
 3400: # Multiple things need this
 3401: sub getReturnHash {
 3402:     my $self = shift;
 3403:     
 3404:     if (!defined($self->{RETURN_HASH})) {
 3405:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
 3406:         $self->{RETURN_HASH} = \%tmpHash;
 3407:     }
 3408: }       
 3409: 
 3410: ######
 3411: # Status queries
 3412: ######
 3413: 
 3414: # These methods query the status of problems.
 3415: 
 3416: # If we need to count parts, this function determines the number of
 3417: # parts from the metadata. When called, it returns a reference to a list
 3418: # of strings corresponding to the parts. (Thus, using it in a scalar context
 3419: # tells you how many parts you have in the problem:
 3420: # $partcount = scalar($resource->countParts());
 3421: # Don't use $self->{PARTS} directly because you don't know if it's been
 3422: # computed yet.
 3423: 
 3424: =pod
 3425: 
 3426: =head2 Resource misc
 3427: 
 3428: Misc. functions for the resource.
 3429: 
 3430: =over 4
 3431: 
 3432: =item * B<hasDiscussion>:
 3433: 
 3434: Returns a false value if there has been discussion since the user last
 3435: logged in, true if there has. Always returns false if the discussion
 3436: data was not extracted when the nav map was constructed.
 3437: 
 3438: =item * B<getFeedback>:
 3439: 
 3440: Gets the feedback for the resource and returns the raw feedback string
 3441: for the resource, or the null string if there is no feedback or the
 3442: email data was not extracted when the nav map was constructed. Usually
 3443: used like this:
 3444: 
 3445:  for (split(/\,/, $res->getFeedback())) {
 3446:     my $link = &Apache::lonnet::escape($_);
 3447:     ...
 3448: 
 3449: and use the link as appropriate.
 3450: 
 3451: =cut
 3452: 
 3453: sub hasDiscussion {
 3454:     my $self = shift;
 3455:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
 3456: }
 3457: 
 3458: sub getFeedback {
 3459:     my $self = shift;
 3460:     my $source = $self->src();
 3461:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
 3462:     return $self->{NAV_MAP}->getFeedback($source);
 3463: }
 3464: 
 3465: sub getErrors {
 3466:     my $self = shift;
 3467:     my $source = $self->src();
 3468:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
 3469:     return $self->{NAV_MAP}->getErrors($source);
 3470: }
 3471: 
 3472: =pod
 3473: 
 3474: =item * B<parts>():
 3475: 
 3476: Returns a list reference containing sorted strings corresponding to
 3477: each part of the problem. Single part problems have only a part '0'.
 3478: Multipart problems do not return their part '0', since they typically
 3479: do not really matter. 
 3480: 
 3481: =item * B<countParts>():
 3482: 
 3483: Returns the number of parts of the problem a student can answer. Thus,
 3484: for single part problems, returns 1. For multipart, it returns the
 3485: number of parts in the problem, not including psuedo-part 0. 
 3486: 
 3487: =item * B<multipart>():
 3488: 
 3489: Returns true if the problem is multipart, false otherwise. Use this instead
 3490: of countParts if all you want is multipart/not multipart.
 3491: 
 3492: =item * B<responseType>($part):
 3493: 
 3494: Returns the response type of the part, without the word "response" on the
 3495: end. Example return values: 'string', 'essay', 'numeric', etc.
 3496: 
 3497: =item * B<responseIds>($part):
 3498: 
 3499: Retreives the response IDs for the given part as an array reference containing
 3500: strings naming the response IDs. This may be empty.
 3501: 
 3502: =back
 3503: 
 3504: =cut
 3505: 
 3506: sub parts {
 3507:     my $self = shift;
 3508: 
 3509:     if ($self->ext) { return []; }
 3510: 
 3511:     $self->extractParts();
 3512:     return $self->{PARTS};
 3513: }
 3514: 
 3515: sub countParts {
 3516:     my $self = shift;
 3517:     
 3518:     my $parts = $self->parts();
 3519: 
 3520:     # If I left this here, then it's not necessary.
 3521:     #my $delta = 0;
 3522:     #for my $part (@$parts) {
 3523:     #    if ($part eq '0') { $delta--; }
 3524:     #}
 3525: 
 3526:     if ($self->{RESOURCE_ERROR}) {
 3527:         return 0;
 3528:     }
 3529: 
 3530:     return scalar(@{$parts}); # + $delta;
 3531: }
 3532: 
 3533: sub multipart {
 3534:     my $self = shift;
 3535:     return $self->countParts() > 1;
 3536: }
 3537: 
 3538: sub singlepart {
 3539:     my $self = shift;
 3540:     return $self->countParts() == 1;
 3541: }
 3542: 
 3543: sub responseType {
 3544:     my $self = shift;
 3545:     my $part = shift;
 3546: 
 3547:     $self->extractParts();
 3548:     if (defined($self->{RESPONSE_TYPES}->{$part})) {
 3549: 	return @{$self->{RESPONSE_TYPES}->{$part}};
 3550:     } else {
 3551: 	return undef;
 3552:     }
 3553: }
 3554: 
 3555: sub responseIds {
 3556:     my $self = shift;
 3557:     my $part = shift;
 3558: 
 3559:     $self->extractParts();
 3560:     if (defined($self->{RESPONSE_IDS}->{$part})) {
 3561: 	return @{$self->{RESPONSE_IDS}->{$part}};
 3562:     } else {
 3563: 	return undef;
 3564:     }
 3565: }
 3566: 
 3567: # Private function: Extracts the parts information, both part names and
 3568: # part types, and saves it. 
 3569: sub extractParts { 
 3570:     my $self = shift;
 3571:     
 3572:     return if (defined($self->{PARTS}));
 3573:     return if ($self->ext);
 3574: 
 3575:     $self->{PARTS} = [];
 3576: 
 3577:     my %parts;
 3578: 
 3579:     # Retrieve part count, if this is a problem
 3580:     if ($self->is_problem()) {
 3581: 	my $partorder;
 3582: 	# Hypothetically, replace previous line with:
 3583: 	# my $partorder = &Apache::lonnet::metadata($self->src(), 'partorder');
 3584: 	# and it'll all work...
 3585:         my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
 3586: 
 3587: 	if ($partorder) {
 3588: 	    my @parts;
 3589: 	    for my $part (split (/,/,$partorder)) {
 3590: 		if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
 3591: 		    push @parts, $part;
 3592: 		}
 3593: 	    }
 3594: 	    $self->{PARTS} = \@parts;
 3595: 	} else {
 3596: 	    if (!$metadata) {
 3597: 		$self->{RESOURCE_ERROR} = 1;
 3598: 		$self->{PARTS} = [];
 3599: 		$self->{PART_TYPE} = {};
 3600: 		return;
 3601: 	    }
 3602: 	    foreach (split(/\,/,$metadata)) {
 3603: 		if ($_ =~ /^part_(.*)$/) {
 3604: 		    my $part = $1;
 3605: 		    # This floods the logs if it blows up
 3606: 		    if (defined($parts{$part})) {
 3607: 			Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->symb());
 3608: 		      }
 3609: 		    
 3610: 		    # check to see if part is turned off.
 3611: 		    
 3612: 		    if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
 3613: 			$parts{$part} = 1;
 3614: 		    }
 3615: 		}
 3616: 	    }
 3617: 	    my @sortedParts = sort keys %parts;
 3618: 	    $self->{PARTS} = \@sortedParts;
 3619:         }
 3620:         
 3621: 
 3622:         my %responseIdHash;
 3623:         my %responseTypeHash;
 3624: 
 3625: 
 3626:         # Init the responseIdHash
 3627:         foreach (@{$self->{PARTS}}) {
 3628:             $responseIdHash{$_} = [];
 3629:         }
 3630: 
 3631:         # Now, the unfortunate thing about this is that parts, part name, and
 3632:         # response id are delimited by underscores, but both the part
 3633:         # name and response id can themselves have underscores in them.
 3634:         # So we have to use our knowlege of part names to figure out 
 3635:         # where the part names begin and end, and even then, it is possible
 3636:         # to construct ambiguous situations.
 3637:         foreach (split /,/, $metadata) {
 3638:             if ($_ =~ /^([a-zA-Z]+)response_(.*)/) {
 3639:                 my $responseType = $1;
 3640:                 my $partStuff = $2;
 3641:                 my $partIdSoFar = '';
 3642:                 my @partChunks = split /_/, $partStuff;
 3643:                 my $i = 0;
 3644: 
 3645:                 for ($i = 0; $i < scalar(@partChunks); $i++) {
 3646:                     if ($partIdSoFar) { $partIdSoFar .= '_'; }
 3647:                     $partIdSoFar .= $partChunks[$i];
 3648:                     if ($parts{$partIdSoFar}) {
 3649:                         my @otherChunks = @partChunks[$i+1..$#partChunks];
 3650:                         my $responseId = join('_', @otherChunks);
 3651:                         push @{$responseIdHash{$partIdSoFar}}, $responseId;
 3652:                         push @{$responseTypeHash{$partIdSoFar}}, $responseType;
 3653:                     }
 3654:                 }
 3655:             }
 3656:         }
 3657: 
 3658:         $self->{RESPONSE_IDS} = \%responseIdHash;
 3659:         $self->{RESPONSE_TYPES} = \%responseTypeHash;
 3660:     }
 3661: 
 3662:     return;
 3663: }
 3664: 
 3665: =pod
 3666: 
 3667: =head2 Resource Status
 3668: 
 3669: Problem resources have status information, reflecting their various
 3670: dates and completion statuses.
 3671: 
 3672: There are two aspects to the status: the date-related information and
 3673: the completion information.
 3674: 
 3675: Idiomatic usage of these two methods would probably look something
 3676: like
 3677: 
 3678:  foreach ($resource->parts()) {
 3679:     my $dateStatus = $resource->getDateStatus($_);
 3680:     my $completionStatus = $resource->getCompletionStatus($_);
 3681: 
 3682:     or
 3683: 
 3684:     my $status = $resource->status($_);
 3685: 
 3686:     ... use it here ...
 3687:  }
 3688: 
 3689: Which you use depends on exactly what you are looking for. The
 3690: status() function has been optimized for the nav maps display and may
 3691: not precisely match what you need elsewhere.
 3692: 
 3693: The symbolic constants shown below can be accessed through the
 3694: resource object: C<$res->OPEN>.
 3695: 
 3696: =over 4
 3697: 
 3698: =item * B<getDateStatus>($part):
 3699: 
 3700: ($part defaults to 0). A convenience function that returns a symbolic
 3701: constant telling you about the date status of the part. The possible
 3702: return values are:
 3703: 
 3704: =back
 3705: 
 3706: B<Date Codes>
 3707: 
 3708: =over 4
 3709: 
 3710: =item * B<OPEN_LATER>:
 3711: 
 3712: The problem will be opened later.
 3713: 
 3714: =item * B<OPEN>:
 3715: 
 3716: Open and not yet due.
 3717: 
 3718: 
 3719: =item * B<PAST_DUE_ANSWER_LATER>:
 3720: 
 3721: The due date has passed, but the answer date has not yet arrived.
 3722: 
 3723: =item * B<PAST_DUE_NO_ANSWER>:
 3724: 
 3725: The due date has passed and there is no answer opening date set.
 3726: 
 3727: =item * B<ANSWER_OPEN>:
 3728: 
 3729: The answer date is here.
 3730: 
 3731: =item * B<NETWORK_FAILURE>:
 3732: 
 3733: The information is unknown due to network failure.
 3734: 
 3735: =back
 3736: 
 3737: =cut
 3738: 
 3739: # Apparently the compiler optimizes these into constants automatically
 3740: sub OPEN_LATER             { return 0; }
 3741: sub OPEN                   { return 1; }
 3742: sub PAST_DUE_NO_ANSWER     { return 2; }
 3743: sub PAST_DUE_ANSWER_LATER  { return 3; }
 3744: sub ANSWER_OPEN            { return 4; }
 3745: sub NOTHING_SET            { return 5; } 
 3746: sub NETWORK_FAILURE        { return 100; }
 3747: 
 3748: # getDateStatus gets the date status for a given problem part. 
 3749: # Because answer date, due date, and open date are fully independent
 3750: # (i.e., it is perfectly possible to *only* have an answer date), 
 3751: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 3752: # (past, future, none given). This function handles this with a decision
 3753: # tree. Read the comments to follow the decision tree.
 3754: 
 3755: sub getDateStatus {
 3756:     my $self = shift;
 3757:     my $part = shift;
 3758:     $part = "0" if (!defined($part));
 3759: 
 3760:     # Always return network failure if there was one.
 3761:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 3762: 
 3763:     my $now = time();
 3764: 
 3765:     my $open = $self->opendate($part);
 3766:     my $due = $self->duedate($part);
 3767:     my $answer = $self->answerdate($part);
 3768: 
 3769:     if (!$open && !$due && !$answer) {
 3770:         # no data on the problem at all
 3771:         # should this be the same as "open later"? think multipart.
 3772:         return $self->NOTHING_SET;
 3773:     }
 3774:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 3775:     if (!$due || $now < $due) {return $self->OPEN}
 3776:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 3777:     if ($answer) { return $self->ANSWER_OPEN; }
 3778:     return PAST_DUE_NO_ANSWER;
 3779: }
 3780: 
 3781: =pod
 3782: 
 3783: B<>
 3784: 
 3785: =over 4
 3786: 
 3787: =item * B<getCompletionStatus>($part):
 3788: 
 3789: ($part defaults to 0.) A convenience function that returns a symbolic
 3790: constant telling you about the completion status of the part, with the
 3791: following possible results:
 3792: 
 3793: =back
 3794: 
 3795: B<Completion Codes>
 3796: 
 3797: =over 4
 3798: 
 3799: =item * B<NOT_ATTEMPTED>:
 3800: 
 3801: Has not been attempted at all.
 3802: 
 3803: =item * B<INCORRECT>:
 3804: 
 3805: Attempted, but wrong by student.
 3806: 
 3807: =item * B<INCORRECT_BY_OVERRIDE>:
 3808: 
 3809: Attempted, but wrong by instructor override.
 3810: 
 3811: =item * B<CORRECT>:
 3812: 
 3813: Correct or correct by instructor.
 3814: 
 3815: =item * B<CORRECT_BY_OVERRIDE>:
 3816: 
 3817: Correct by instructor override.
 3818: 
 3819: =item * B<EXCUSED>:
 3820: 
 3821: Excused. Not yet implemented.
 3822: 
 3823: =item * B<NETWORK_FAILURE>:
 3824: 
 3825: Information not available due to network failure.
 3826: 
 3827: =item * B<ATTEMPTED>:
 3828: 
 3829: Attempted, and not yet graded.
 3830: 
 3831: =back
 3832: 
 3833: =cut
 3834: 
 3835: sub NOT_ATTEMPTED         { return 10; }
 3836: sub INCORRECT             { return 11; }
 3837: sub INCORRECT_BY_OVERRIDE { return 12; }
 3838: sub CORRECT               { return 13; }
 3839: sub CORRECT_BY_OVERRIDE   { return 14; }
 3840: sub EXCUSED               { return 15; }
 3841: sub ATTEMPTED             { return 16; }
 3842: 
 3843: sub getCompletionStatus {
 3844:     my $self = shift;
 3845:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 3846: 
 3847:     my $status = $self->queryRestoreHash('solved', shift);
 3848: 
 3849:     # Left as seperate if statements in case we ever do more with this
 3850:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 3851:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
 3852:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 3853:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 3854:     if ($status eq 'excused') {return $self->EXCUSED; }
 3855:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
 3856:     return $self->NOT_ATTEMPTED;
 3857: }
 3858: 
 3859: sub queryRestoreHash {
 3860:     my $self = shift;
 3861:     my $hashentry = shift;
 3862:     my $part = shift;
 3863:     $part = "0" if (!defined($part) || $part eq '');
 3864:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 3865: 
 3866:     $self->getReturnHash();
 3867: 
 3868:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
 3869: }
 3870: 
 3871: =pod
 3872: 
 3873: B<Composite Status>
 3874: 
 3875: Along with directly returning the date or completion status, the
 3876: resource object includes a convenience function B<status>() that will
 3877: combine the two status tidbits into one composite status that can
 3878: represent the status of the resource as a whole. This method represents
 3879: the concept of the thing we want to display to the user on the nav maps
 3880: screen, which is a combination of completion and open status. The precise logic is
 3881: documented in the comments of the status method. The following results
 3882: may be returned, all available as methods on the resource object
 3883: ($res->NETWORK_FAILURE): In addition to the return values that match
 3884: the date or completion status, this function can return "ANSWER_SUBMITTED"
 3885: if that problemstatus parameter value is set to No, suppressing the
 3886: incorrect/correct feedback.
 3887: 
 3888: =over 4
 3889: 
 3890: =item * B<NETWORK_FAILURE>:
 3891: 
 3892: The network has failed and the information is not available.
 3893: 
 3894: =item * B<NOTHING_SET>:
 3895: 
 3896: No dates have been set for this problem (part) at all. (Because only
 3897: certain parts of a multi-part problem may be assigned, this can not be
 3898: collapsed into "open later", as we do not know a given part will EVER
 3899: be opened. For single part, this is the same as "OPEN_LATER".)
 3900: 
 3901: =item * B<CORRECT>:
 3902: 
 3903: For any reason at all, the part is considered correct.
 3904: 
 3905: =item * B<EXCUSED>:
 3906: 
 3907: For any reason at all, the problem is excused.
 3908: 
 3909: =item * B<PAST_DUE_NO_ANSWER>:
 3910: 
 3911: The problem is past due, not considered correct, and no answer date is
 3912: set.
 3913: 
 3914: =item * B<PAST_DUE_ANSWER_LATER>:
 3915: 
 3916: The problem is past due, not considered correct, and an answer date in
 3917: the future is set.
 3918: 
 3919: =item * B<ANSWER_OPEN>:
 3920: 
 3921: The problem is past due, not correct, and the answer is now available.
 3922: 
 3923: =item * B<OPEN_LATER>:
 3924: 
 3925: The problem is not yet open.
 3926: 
 3927: =item * B<TRIES_LEFT>:
 3928: 
 3929: The problem is open, has been tried, is not correct, but there are
 3930: tries left.
 3931: 
 3932: =item * B<INCORRECT>:
 3933: 
 3934: The problem is open, and all tries have been used without getting the
 3935: correct answer.
 3936: 
 3937: =item * B<OPEN>:
 3938: 
 3939: The item is open and not yet tried.
 3940: 
 3941: =item * B<ATTEMPTED>:
 3942: 
 3943: The problem has been attempted.
 3944: 
 3945: =item * B<ANSWER_SUBMITTED>:
 3946: 
 3947: An answer has been submitted, but the student should not see it.
 3948: 
 3949: =back
 3950: 
 3951: =cut
 3952: 
 3953: sub TRIES_LEFT       { return 20; }
 3954: sub ANSWER_SUBMITTED { return 21; }
 3955: 
 3956: sub status {
 3957:     my $self = shift;
 3958:     my $part = shift;
 3959:     if (!defined($part)) { $part = "0"; }
 3960:     my $completionStatus = $self->getCompletionStatus($part);
 3961:     my $dateStatus = $self->getDateStatus($part);
 3962: 
 3963:     # What we have is a two-dimensional matrix with 4 entries on one
 3964:     # dimension and 5 entries on the other, which we want to colorize,
 3965:     # plus network failure and "no date data at all".
 3966: 
 3967:     #if ($self->{RESOURCE_ERROR}) { return NETWORK_FAILURE; }
 3968:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 3969: 
 3970:     my $suppressFeedback = $self->problemstatus($part) eq 'no';
 3971:     # If there's an answer date and we're past it, don't
 3972:     # suppress the feedback; student should know
 3973:     if ($self->answerdate($part) && $self->answerdate($part) < time()) {
 3974: 	$suppressFeedback = 0;
 3975:     }
 3976: 
 3977:     # There are a few whole rows we can dispose of:
 3978:     if ($completionStatus == CORRECT ||
 3979:         $completionStatus == CORRECT_BY_OVERRIDE ) {
 3980:         return $suppressFeedback? ANSWER_SUBMITTED : CORRECT; 
 3981:     }
 3982: 
 3983:     if ($completionStatus == ATTEMPTED) {
 3984:         return ATTEMPTED;
 3985:     }
 3986: 
 3987:     # If it's EXCUSED, then return that no matter what
 3988:     if ($completionStatus == EXCUSED) {
 3989:         return EXCUSED; 
 3990:     }
 3991: 
 3992:     if ($dateStatus == NOTHING_SET) {
 3993:         return NOTHING_SET;
 3994:     }
 3995: 
 3996:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
 3997:     # by 4 matrix (date statuses).
 3998: 
 3999:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 4000:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 4001:         return $dateStatus; 
 4002:     }
 4003: 
 4004:     if ($dateStatus == ANSWER_OPEN) {
 4005:         return ANSWER_OPEN;
 4006:     }
 4007: 
 4008:     # Now: (incorrect, incorrect_override, not_attempted) x 
 4009:     # (open_later), (open)
 4010:     
 4011:     if ($dateStatus == OPEN_LATER) {
 4012:         return OPEN_LATER;
 4013:     }
 4014: 
 4015:     # If it's WRONG...
 4016:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
 4017:         # and there are TRIES LEFT:
 4018:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
 4019:             return $suppressFeedback ? ANSWER_SUBMITTED : TRIES_LEFT;
 4020:         }
 4021:         return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
 4022:     }
 4023: 
 4024:     # Otherwise, it's untried and open
 4025:     return OPEN; 
 4026: }
 4027: 
 4028: sub CLOSED { return 23; }
 4029: sub ERROR { return 24; }
 4030: 
 4031: =pod
 4032: 
 4033: B<Simple Status>
 4034: 
 4035: Convenience method B<simpleStatus> provides a "simple status" for the resource.
 4036: "Simple status" corresponds to "which icon is shown on the
 4037: Navmaps". There are six "simple" statuses:
 4038: 
 4039: =over 4
 4040: 
 4041: =item * B<CLOSED>: The problem is currently closed. (No icon shown.)
 4042: 
 4043: =item * B<OPEN>: The problem is open and unattempted.
 4044: 
 4045: =item * B<CORRECT>: The problem is correct for any reason.
 4046: 
 4047: =item * B<INCORRECT>: The problem is incorrect and can still be
 4048: completed successfully.
 4049: 
 4050: =item * B<ATTEMPTED>: The problem has been attempted, but the student
 4051: does not know if they are correct. (The ellipsis icon.)
 4052: 
 4053: =item * B<ERROR>: There is an error retrieving information about this
 4054: problem.
 4055: 
 4056: =back
 4057: 
 4058: =cut
 4059: 
 4060: # This hash maps the composite status to this simple status, and
 4061: # can be used directly, if you like
 4062: my %compositeToSimple = 
 4063:     (
 4064:       NETWORK_FAILURE()       => ERROR,
 4065:       NOTHING_SET()           => CLOSED,
 4066:       CORRECT()               => CORRECT,
 4067:       EXCUSED()               => CORRECT,
 4068:       PAST_DUE_NO_ANSWER()    => INCORRECT,
 4069:       PAST_DUE_ANSWER_LATER() => INCORRECT,
 4070:       ANSWER_OPEN()           => INCORRECT,
 4071:       OPEN_LATER()            => CLOSED,
 4072:       TRIES_LEFT()            => OPEN,
 4073:       INCORRECT()             => INCORRECT,
 4074:       OPEN()                  => OPEN,
 4075:       ATTEMPTED()             => ATTEMPTED,
 4076:       ANSWER_SUBMITTED()      => ATTEMPTED
 4077:      );
 4078: 
 4079: sub simpleStatus {
 4080:     my $self = shift;
 4081:     my $part = shift;
 4082:     my $status = $self->status($part);
 4083:     return $compositeToSimple{$status};
 4084: }
 4085: 
 4086: =pod
 4087: 
 4088: B<simpleStatusCount> will return an array reference containing, in
 4089: this order, the number of OPEN, CLOSED, CORRECT, INCORRECT, ATTEMPTED,
 4090: and ERROR parts the given problem has.
 4091: 
 4092: =cut
 4093:     
 4094: # This maps the status to the slot we want to increment
 4095: my %statusToSlotMap = 
 4096:     (
 4097:      OPEN()      => 0,
 4098:      CLOSED()    => 1,
 4099:      CORRECT()   => 2,
 4100:      INCORRECT() => 3,
 4101:      ATTEMPTED() => 4,
 4102:      ERROR()     => 5
 4103:      );
 4104: 
 4105: sub statusToSlot { return $statusToSlotMap{shift()}; }
 4106: 
 4107: sub simpleStatusCount {
 4108:     my $self = shift;
 4109: 
 4110:     my @counts = (0, 0, 0, 0, 0, 0, 0);
 4111:     foreach my $part (@{$self->parts()}) {
 4112: 	$counts[$statusToSlotMap{$self->simpleStatus($part)}]++;
 4113:     }
 4114: 
 4115:     return \@counts;
 4116: }
 4117: 
 4118: =pod
 4119: 
 4120: B<Completable>
 4121: 
 4122: The completable method represents the concept of I<whether the student can
 4123: currently do the problem>. If the student can do the problem, which means
 4124: that it is open, there are tries left, and if the problem is manually graded
 4125: or the grade is suppressed via problemstatus, the student has not tried it
 4126: yet, then the method returns 1. Otherwise, it returns 0, to indicate that 
 4127: either the student has tried it and there is no feedback, or that for
 4128: some reason it is no longer completable (not open yet, successfully completed,
 4129: out of tries, etc.). As an example, this is used as the filter for the
 4130: "Uncompleted Homework" option for the nav maps.
 4131: 
 4132: If this does not quite meet your needs, do not fiddle with it (unless you are
 4133: fixing it to better match the student's conception of "completable" because
 4134: it's broken somehow)... make a new method.
 4135: 
 4136: =cut
 4137: 
 4138: sub completable {
 4139:     my $self = shift;
 4140:     if (!$self->is_problem()) { return 0; }
 4141:     my $partCount = $self->countParts();
 4142: 
 4143:     foreach my $part (@{$self->parts()}) {
 4144:         if ($part eq '0' && $partCount != 1) { next; }
 4145:         my $status = $self->status($part);
 4146:         # "If any of the parts are open, or have tries left (implies open),
 4147:         # and it is not "attempted" (manually graded problem), it is
 4148:         # not "complete"
 4149: 	if ($self->getCompletionStatus($part) == ATTEMPTED() ||
 4150: 	    $status == ANSWER_SUBMITTED() ) {
 4151: 	    # did this part already, as well as we can
 4152: 	    next;
 4153: 	}
 4154: 	if ($status == OPEN() || $status == TRIES_LEFT()) {
 4155: 	    return 1;
 4156: 	}
 4157:     }
 4158:         
 4159:     # If all the parts were complete, so was this problem.
 4160:     return 0;
 4161: }
 4162: 
 4163: =pod
 4164: 
 4165: =head2 Resource/Nav Map Navigation
 4166: 
 4167: =over 4
 4168: 
 4169: =item * B<getNext>():
 4170: 
 4171: Retreive an array of the possible next resources after this
 4172: one. Always returns an array, even in the one- or zero-element case.
 4173: 
 4174: =item * B<getPrevious>():
 4175: 
 4176: Retreive an array of the possible previous resources from this
 4177: one. Always returns an array, even in the one- or zero-element case.
 4178: 
 4179: =cut
 4180: 
 4181: sub getNext {
 4182:     my $self = shift;
 4183:     my @branches;
 4184:     my $to = $self->to();
 4185:     foreach my $branch ( split(/,/, $to) ) {
 4186:         my $choice = $self->{NAV_MAP}->getById($branch);
 4187:         my $next = $choice->goesto();
 4188:         $next = $self->{NAV_MAP}->getById($next);
 4189: 
 4190:         push @branches, $next;
 4191:     }
 4192:     return \@branches;
 4193: }
 4194: 
 4195: sub getPrevious {
 4196:     my $self = shift;
 4197:     my @branches;
 4198:     my $from = $self->from();
 4199:     foreach my $branch ( split /,/, $from) {
 4200:         my $choice = $self->{NAV_MAP}->getById($branch);
 4201:         my $prev = $choice->comesfrom();
 4202:         $prev = $self->{NAV_MAP}->getById($prev);
 4203: 
 4204:         push @branches, $prev;
 4205:     }
 4206:     return \@branches;
 4207: }
 4208: 
 4209: sub browsePriv {
 4210:     my $self = shift;
 4211:     if (defined($self->{BROWSE_PRIV})) {
 4212:         return $self->{BROWSE_PRIV};
 4213:     }
 4214: 
 4215:     $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
 4216: }
 4217: 
 4218: =pod
 4219: 
 4220: =back
 4221: 
 4222: =cut
 4223: 
 4224: 1;
 4225: 
 4226: __END__
 4227: 
 4228: 

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