File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.184: download - view: text, annotated - select for diffs
Mon May 5 17:44:03 2003 UTC (21 years, 1 month ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Should fix bug 1347 "Students want to jump to first do-able homework
assignment."

Speed note: In ADV205, the huge course with tons of maps that have 100 choose
10 resources, it takes 12 seconds to scan the entire course and conclude that
there are no currently completable homework problems.

There may be some interaction with multi-part problems and/or essay response
problems that have to be graded by an instructor. I'm looking into that.

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

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