File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.179: download - view: text, annotated - select for diffs
Tue Apr 22 18:38:47 2003 UTC (21 years, 1 month ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Oops, we haven't done "get_unprocessed_cgi" yet; need to check querystring
directly.

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

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