File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.133: download - view: text, annotated - select for diffs
Fri Jan 31 22:46:50 2003 UTC (21 years, 4 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
First column now works mostly correctly. That should be the hardest
by far of the four to convert.

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

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