File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.196: download - view: text, annotated - select for diffs
Tue Jun 10 18:42:18 2003 UTC (21 years ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Remove debugging info.

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

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