File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.185: download - view: text, annotated - select for diffs
Mon May 12 18:22:38 2003 UTC (21 years, 1 month ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Fix bug 1430 "problems never see themselves as correct".

Fix bug #628 for nav maps, honoring the problemstatus flag, assuming
'No" is the value that turns that off and everything else means "Yes".

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

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