File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.263: download - view: text, annotated - select for diffs
Mon Jun 28 15:09:13 2004 UTC (19 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- first check parm then extension (parm might be overriding extension, need to default to extension)

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

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