File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.259: download - view: text, annotated - select for diffs
Wed May 5 21:04:14 2004 UTC (20 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Posts in discussions now identified as "NEW" if posts were added since user's last visit to resource or bulletin board.  "Speech bubbles" in NAVMAP also displayed for each resource or bulletin board if posts have been added since last visit.

User can set display to be all posts, or only unread posts.  To support cases where there are several "NEW" posts, the time of the previous visit is passed in a query string during hide/make visible, reply or delete operations so that the differentiation of "NEW" posts is retained until the user leaves the bulletin board.  This behavior does not currently apply to discussions associated with resources.

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

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