File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.142: download - view: text, annotated - select for diffs
Fri Feb 7 22:17:51 2003 UTC (21 years, 3 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
A special commit, just for Matthew.

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

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