File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.203: download - view: text, annotated - select for diffs
Fri Jun 13 13:58:06 2003 UTC (20 years, 11 months ago) by bowersj2
Branches: MAIN
CVS tags: version_0_99_2, HEAD
I'm hearing too much confusion about what maps are linked on the nav
screen. All maps are now unlinked.

If we want to change it back, we need to make doc maps linkable.

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

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