File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.221: download - view: text, annotated - select for diffs
Thu Aug 7 17:26:44 2003 UTC (20 years, 10 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
lonnavmaps are now maximally lazy; no processing is performed until it
is needed, except in cases where it makes sense to grab all data for the
course at a time.

As a result, the Apache::lonnavmaps::navmap->new() call no longer needs
any arguments; it assumes you're using the current user's navmaps and
generates the other data as needed.

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

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