File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.216: download - view: text, annotated - select for diffs
Thu Jul 17 18:40:49 2003 UTC (20 years, 10 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Major documentation updates; also a fix for the Uncompleted Homework
view; logic was broken and the view was suppressing multipart problems
that had *any* part done. So if there's a multipart problem with 20
parts, as soon as you completed one, it would disappear from the
Uncompleted Homework screen. Ick.

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

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