File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.110: download - view: text, annotated - select for diffs
Fri Nov 15 20:12:11 2002 UTC (21 years, 6 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Closes bug 964 "Nav map loses your place if you Open All Folders."

    1: 
    2: # The LearningOnline Network with CAPA
    3: # Navigate Maps Handler
    4: #
    5: # $Id: lonnavmaps.pm,v 1.110 2002/11/15 20:12:11 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: sub handler {
   50:     my $r = shift;
   51: 
   52:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
   53: 
   54:     # Handle header-only request
   55:     if ($r->header_only) {
   56:         if ($ENV{'browser.mathml'}) {
   57:             $r->content_type('text/xml');
   58:         } else {
   59:             $r->content_type('text/html');
   60:         }
   61:         $r->send_http_header;
   62:         return OK;
   63:     }
   64: 
   65:     # Send header, don't cache this page
   66:     if ($ENV{'browser.mathml'}) {
   67:         $r->content_type('text/xml');
   68:     } else {
   69:         $r->content_type('text/html');
   70:     }
   71:     &Apache::loncommon::no_cache($r);
   72:     $r->send_http_header;
   73: 
   74:     # Create the nav map
   75:     my $navmap = Apache::lonnavmaps::navmap->new(
   76:                         $ENV{"request.course.fn"}.".db",
   77:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
   78: 
   79: 
   80:     if (!defined($navmap)) {
   81:         my $requrl = $r->uri;
   82:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
   83:         return HTTP_NOT_ACCEPTABLE;
   84:     }
   85: 
   86:     # Header
   87:     $r->print(&Apache::loncommon::bodytag('Navigate Course Map','',
   88:                                           ''));
   89:     $r->print('<script>window.focus();</script>');
   90: 
   91:     $r->print('<table border="0" cellpadding="2" cellspacing="0">');
   92:     my $date=localtime;
   93:     $r->print('<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>');
   94: 
   95:     # Print discussions and feedback header
   96:     if ($navmap->{LAST_CHECK}) {
   97:         $r->print('<td align="center" valign="bottom">&nbsp;&nbsp;'.
   98:                   '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
   99:                   strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
  100:                   '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
  101:                   '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
  102:                   '</td>'); 
  103:     } else {
  104:         $r->print('<td align="center" valign="bottom">&nbsp;&nbsp;'.
  105:                   '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
  106:                   '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
  107:                   '</td>'); 
  108:     }
  109:     $r->print('</tr></table>');
  110: 
  111:     my $condition = 0;
  112:     if ($ENV{'form.condition'}) {
  113:         $condition = 1;
  114:     }
  115: 
  116:     my $currenturl = $ENV{'form.postdata'};
  117:     $currenturl=~s/^http\:\/\///;
  118:     $currenturl=~s/^[^\/]+//;
  119: 
  120:     # alreadyHere allows us to only open the maps necessary to view
  121:     # the current location once, while at the same time remembering
  122:     # the current location. Without that check, the user would never
  123:     # be able to close those maps; the user would close it, and the
  124:     # currenturl scan would re-open it.
  125:     my $queryAdd = "postdata=" . &Apache::lonnet::escape($currenturl) .
  126:         "&alreadyHere=1";
  127: 
  128:     if ($condition) {
  129:         $r->print("<a href=\"navmaps?condition=0&filter=&$queryAdd\">Close All Folders</a>");
  130:     } else {
  131:         $r->print("<a href=\"navmaps?condition=1&filter=&$queryAdd\">Open All Folders</a>");
  132:     }
  133: 
  134:     $r->print('<br>&nbsp;');
  135:     $r->rflush();
  136: 
  137:     # Now that we've displayed some stuff to the user, init the navmap
  138:     $navmap->init();
  139: 
  140:     # Check that it's defined
  141:     if (!($navmap->courseMapDefined())) {
  142:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
  143:                   '</body></html>');
  144:         return OK;
  145:     }
  146: 
  147:     # Grab a resource object so we have access to the constants; this
  148:     # is technically not proper, but should be harmless
  149:     my $res = $navmap->firstResource();
  150: 
  151:     # These are some data tables, which make it easy to change some of
  152:     # of the specific visualization parameters if desired.
  153: 
  154:     # Defines a status->color mapping, null string means don't color
  155:     my %colormap = 
  156:     ( $res->NETWORK_FAILURE        => '',
  157:       $res->CORRECT                => '',
  158:       $res->EXCUSED                => '#BBBBFF',
  159:       $res->PAST_DUE_ANSWER_LATER  => '',
  160:       $res->PAST_DUE_NO_ANSWER     => '',
  161:       $res->ANSWER_OPEN            => '#CCFFCC',
  162:       $res->OPEN_LATER             => '',
  163:       $res->TRIES_LEFT             => '',
  164:       $res->INCORRECT              => '',
  165:       $res->OPEN                   => '',
  166:       $res->NOTHING_SET            => ''        );
  167:     # And a special case in the nav map; what to do when the assignment
  168:     # is not yet done and due in less then 24 hours
  169:     my $hurryUpColor = "#FF0000";
  170: 
  171:     my %statusIconMap = 
  172:         ( $res->NETWORK_FAILURE    => '',
  173:           $res->NOTHING_SET        => '',
  174:           $res->CORRECT            => 'navmap.correct.gif',
  175:           $res->EXCUSED            => 'navmap.correct.gif',
  176:           $res->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
  177:           $res->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
  178:           $res->ANSWER_OPEN        => 'navmap.wrong.gif',
  179:           $res->OPEN_LATER         => '',
  180:           $res->TRIES_LEFT         => 'navmap.open.gif',
  181:           $res->INCORRECT          => 'navmap.wrong.gif',
  182:           $res->OPEN               => 'navmap.open.gif',
  183:           $res->ATTEMPTED          => 'navmap.open.gif' );
  184: 
  185:     my %iconAltTags = 
  186:         ( 'navmap.correct.gif' => 'Correct',
  187:           'navmap.wrong.gif'   => 'Incorrect',
  188:           'navmap.open.gif'    => 'Open' );
  189: 
  190:     my %condenseStatuses =
  191:         ( $res->NETWORK_FAILURE    => 1,
  192:           $res->NOTHING_SET        => 1,
  193:           $res->CORRECT            => 1 );
  194: 
  195:     my %filterHash;
  196:     # Figure out what we're not displaying
  197:     foreach (split(/\,/, $ENV{"form.filter"})) {
  198:         if ($_) {
  199:             $filterHash{$_} = "1";
  200:         }
  201:     }
  202: 
  203:     # Is this a new-style course? If so, we want to suppress showing the top-level
  204:     # maps in their own folders, in favor of "inlining" them.
  205:     my $topResource = $navmap->getById("0.0");
  206:     my $inlineTopLevelMaps = $topResource->src() =~ m|^/uploaded/.*default\.sequence$|;
  207: 
  208:     # Begin the HTML table
  209:     # four cols: resource + indent, chat+feedback, icon, text string
  210:     $r->print('<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n");
  211: 
  212:     # This needs to be updated to use symbs from the remote, 
  213:     # instead of uris. The changes to this and the main rendering
  214:     # loop should be obvious.
  215:     # Here's a simple example of the iterator.
  216:     # Preprocess the map: Look for current URL, force inlined maps to display
  217: 
  218:     my $mapIterator = $navmap->getIterator(undef, undef, \%filterHash, 1);
  219:     my $found = 0;
  220:     my $depth = 1;
  221:     my $currentUrlIndex = 0; # keeps track of when the current resource is found,
  222:                              # so we can back up a few and put the anchor above the
  223:                              # current resource
  224:     my $currentUrlDelta = 5; # change this to change how many resources are displayed
  225:                              # before the current resource when using #current
  226:     $mapIterator->next(); # discard the first BEGIN_MAP
  227:     my $curRes = $mapIterator->next();
  228:     my $counter = 0;
  229:     
  230:     while ($depth > 0) {
  231:         if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
  232:         if ($curRes == $mapIterator->END_MAP()) { $depth--; }
  233: 
  234:         if (ref($curRes)) { $counter++; }
  235: 
  236:         my $mapStack = $mapIterator->getStack();
  237:         if ($currenturl && !$ENV{'form.alreadyHere'} && ref($curRes) && 
  238:             $curRes->src() eq $currenturl) {
  239:             # If this is the correct resource, be sure to 
  240:             # show it by making sure the containing maps
  241:             # are open.
  242: 
  243:             # This is why we have to use the main iterator instead of the
  244:             # potentially faster DFS: The count has to be the same, so
  245:             # the order has to be the same, which DFS won't give us.
  246:             $currentUrlIndex = $counter;
  247:             
  248:             # Ensure the parent maps are open
  249:             for my $map (@{$mapStack}) {
  250:                 if ($condition) {
  251:                     undef $filterHash{$map->map_pc()};
  252:                 } else {
  253:                     $filterHash{$map->map_pc()} = 1;
  254:                 }
  255:             }
  256:             $ENV{'form.alreadyHere'} = 1;
  257:         }
  258:             
  259:         # Preprocessing: If we're inlining nav maps into the top-level display,
  260:         # make sure we show this map!
  261:         if ($inlineTopLevelMaps && ref($curRes) && $curRes->is_map && 
  262:             scalar(@{$mapStack}) == 1) {
  263:             if ($condition) {
  264:                 undef $filterHash{$curRes->map_pc()};
  265:             } else {
  266:                 $filterHash{$curRes->map_pc()} = 1;
  267:             }
  268:         }
  269: 
  270:         $curRes = $mapIterator->next();
  271:     }
  272:     
  273:     undef $res; # so we don't accidentally use it later
  274:     my $indentLevel = 0;
  275:     my $indentString = "<img src=\"/adm/lonIcons/whitespace1.gif\" width=\"25\" height=\"1\" alt=\"\" border=\"0\" />";
  276: 
  277:     my $isNewBranch = 0;
  278:     my $now = time();
  279:     my $in24Hours = $now + 24 * 60 * 60;
  280:     my $displayedHereMarker = 0;
  281:     
  282:     # We know the first thing is a BEGIN_MAP (see "$self->{STARTED}"
  283:     # code in iterator->next), so ignore the first one
  284:     $mapIterator = $navmap->getIterator(undef, undef, \%filterHash,
  285:                                            $condition);
  286:     $mapIterator->next();
  287:     $curRes = $mapIterator->next();
  288:     my $deltadepth = 0;
  289:     $depth = 1;
  290: 
  291:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
  292:     my $rowNum = 0;
  293: 
  294:     $counter = 0;
  295: 
  296:     # Print the 'current' anchor here if it would fall off the top
  297:     if ($currentUrlIndex - $currentUrlDelta < 0) {
  298:         $r->print('<a name="current" />');
  299:     }
  300: 
  301:     while ($depth > 0) {
  302:         # If this is an inlined map, cancel the shift to the right,
  303:         # which has the effect of making the map look inlined
  304:         if ($inlineTopLevelMaps && scalar(@{$mapIterator->getStack()}) == 1 &&
  305:             ref($curRes) && $curRes->is_map()) {
  306:             $deltadepth = -1;
  307:             $curRes = $mapIterator->next();
  308:             next;
  309:         }
  310: 
  311:         if ($curRes == $mapIterator->BEGIN_MAP() ||
  312:             $curRes == $mapIterator->BEGIN_BRANCH()) {
  313:             $indentLevel++;
  314:         }
  315:         if ($curRes == $mapIterator->END_MAP() ||
  316:             $curRes == $mapIterator->END_BRANCH()) {
  317:             $indentLevel--;
  318:         }
  319:         if ($curRes == $mapIterator->BEGIN_BRANCH()) {
  320:             $isNewBranch = 1;
  321:         }
  322:         if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
  323:         if ($curRes == $mapIterator->END_MAP()) { $depth--; }
  324: 
  325:         if (ref($curRes)) { $counter++; }
  326: 
  327:         if ($depth == 1) { $deltadepth = 0; } # we're done shifting, because we're
  328:                                               # out of the inlined map
  329: 
  330:         # Is this resource being ignored because it is in a random-out
  331:         # map and it was not selected?
  332:         if (ref($curRes) && !advancedUser() && $curRes->randomout()) {
  333:             $curRes = $mapIterator->next();
  334:             next; # if yes, then just ignore this resource
  335:         }
  336: 
  337:         if (ref($curRes) && $curRes->src()) {
  338: 
  339:             # Step one: Decide which parts to show
  340:             my @parts = @{$curRes->parts()};
  341:             my $multipart = scalar(@parts) > 1;
  342:             my $condensed = 0;
  343:                 
  344:             if ($curRes->is_problem()) {
  345: 
  346:                 # Is it multipart?
  347:                 if ($multipart) {
  348:                     # If it's multipart, see if part 0 is "open"
  349:                     # if it is, display all parts, if it isn't,
  350:                     # just display first
  351:                     if (!$curRes->opendate("0")) {
  352:                         # no parts are open, display as one part
  353:                         @parts = ("0");
  354:                         $condensed = 1;
  355:                     } else {
  356:                         # Otherwise, only display part 0 if we want to 
  357:                         # attach feedback or email information to it
  358:                         if ($curRes->hasDiscussion() || $curRes->getFeedback()) {
  359:                             shift @parts;
  360:                         } else {
  361:                             # Now, we decide whether to condense the
  362:                             # parts due to similarity
  363:                             my $status = $curRes->status($parts[1]);
  364:                             my $due = $curRes->duedate($parts[1]);
  365:                             my $open = $curRes->opendate($parts[1]);
  366:                             my $statusAllSame = 1;
  367:                             my $dueAllSame = 1;
  368:                             my $openAllSame = 1;
  369:                             for (my $i = 2; $i < scalar(@parts); $i++) {
  370:                                 if ($curRes->status($parts[$i]) != $status){
  371:                                     $statusAllSame = 0;
  372:                                 }
  373:                                 if ($curRes->duedate($parts[$i]) != $due ) {
  374:                                     $dueAllSame = 0;
  375:                                 }
  376:                                 if ($curRes->opendate($parts[$i]) != $open) {
  377:                                     $openAllSame = 0;
  378:                                 }
  379:                             }
  380:                             
  381:                             # $allSame is true if all the statuses were
  382:                             # the same. Now, if they are all the same and
  383:                             # match one of the statuses to condense, or they
  384:                             # are all open with the same due date, or they are
  385:                             # all OPEN_LATER with the same open date, display the
  386:                             # status of the first non-zero part (to get the 'correct'
  387:                             # status right, since 0 is never 'correct' or 'open').
  388:                             if (($statusAllSame && defined($condenseStatuses{$status})) ||
  389:                                 ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
  390:                                 ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
  391:                                 @parts = ($parts[1]);
  392:                                 $condensed = 1;
  393:                             }
  394:                         }
  395:                     }
  396:                 }
  397: 
  398:             } else {
  399:                 $parts[0] = "0"; # this is to get past foreach loop below
  400:                  # you can consider a non-problem resource as a resource
  401:                   # with only one part without loss, and it simplifies the looping
  402:             }
  403: 
  404:             # Is it a multipart problem with a single part, now in 
  405:             # @parts with "0" filtered out? If so, 'forget' it's a multi-part
  406:             # problem and treat it like a single-part problem.
  407:             if ( scalar(@parts) == 1 ) {
  408:                 $multipart = 0;
  409:             }
  410: 
  411:             # Display one part, in event of network error.
  412:             # If this is a single part, we can at least show the correct
  413:             # status, but if it's multipart, we're lost, since we can't
  414:             # retreive the metadata to count the parts
  415:             if ($curRes->{RESOURCE_ERROR}) {
  416:                 @parts = ("0");
  417:             }
  418: 
  419:             # Step Two: Print the actual data.
  420: 
  421:             # For each part we intend to display...
  422:             foreach my $part (@parts) {
  423: 
  424:                 my $deltalevel = 0; # for inserting the branch icon
  425:                 my $nonLinkedText = ""; # unlinked stuff after title
  426:                 
  427:                 my $stack = $mapIterator->getStack();
  428:                 my $src = getLinkForResource($stack);
  429: 
  430:                 # Pass the correct symb on the querystring, so the
  431:                 # remote will figure out where we are if we click a link
  432:                 my $srcHasQuestion = $src =~ /\?/;
  433:                 my $link = $src.
  434:                     ($srcHasQuestion?'&':'?') .
  435:                     'symb='.&Apache::lonnet::escape($curRes->symb()).
  436:                     '"';
  437: 
  438:                 my $title = $curRes->compTitle();
  439:                 my $partLabel = "";
  440:                 my $newBranchText = "";
  441: 
  442:                 # If this is a new branch, label it so
  443:                 if ($isNewBranch) {
  444:                     $newBranchText = "<img src=\"/adm/lonIcons/branch.gif\" border=\"0\">";
  445:                     $isNewBranch = 0;
  446:                     $deltalevel = 1; # reserves space for the branch icon
  447:                 }
  448: 
  449:                 # links to open and close the folders
  450:                 my $linkopen = "<a href=\"$link\">";
  451:                 my $linkclose = "</a>";
  452: 
  453:                 my $icon = "<img src=\"/adm/lonIcons/html.gif\" alt=\"\" border=\"0\" />";
  454:                 if ($curRes->is_problem()) { 
  455:                     if ($part eq "0" || $condensed) {
  456:                         $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border=\"0\" />'; 
  457:                     } else {
  458:                         $icon = $indentString;
  459:                     }
  460:                 }
  461: 
  462:                 # Display the correct icon, link to open or shut map
  463:                 if ($curRes->is_map()) { 
  464:                     my $mapId = $curRes->map_pc();
  465:                     my $nowOpen = (!defined($filterHash{$mapId}));
  466:                     if ($condition) {$nowOpen = !$nowOpen;}
  467:                     $icon = $nowOpen ?
  468:                         "navmap.folder.closed.gif" : "navmap.folder.open.gif";
  469:                     $icon = "<img src=\"/adm/lonIcons/$icon\" alt=\"\" border=\"0\" />";
  470:                     $linkopen = "<a href=\"/adm/navmaps?filter=";
  471:                     $linkopen .= ($nowOpen xor $condition) ? 
  472:                         addToFilter(\%filterHash, $mapId) :
  473:                         removeFromFilter(\%filterHash, $mapId);
  474:                     $linkopen .= "&condition=$condition&$queryAdd\">";
  475:                     $linkclose = "</a>";
  476: 
  477:                 }
  478:                 
  479:                 my $colorizer = "";
  480:                 my $color;
  481:                 if ($curRes->is_problem()) {
  482:                     my $status = $curRes->status($part);
  483:                     $color = $colormap{$status};
  484: 
  485:                     # Special case in the navmaps: If in less then
  486:                     # 24 hours, give it a bit of urgency
  487:                     if (($status == $curRes->OPEN() || $status == $curRes->ATTEMPTED() ||
  488:                          $status == $curRes->TRIES_LEFT())
  489:                         && $curRes->duedate() &&
  490:                         $curRes->duedate() < time()+(24*60*60) && 
  491:                         $curRes->duedate() > time()) {
  492:                         $color = $hurryUpColor;
  493:                     }
  494:                     # Special case: If this is the last try, and there is
  495:                     # more then one available, and it's not due yet, give a bit of urgency
  496:                     my $tries = $curRes->tries($part);
  497:                     my $maxtries = $curRes->maxtries($part);
  498:                     if ($tries && $maxtries && $maxtries > 1 &&
  499:                         $maxtries - $tries == 1 && $curRes->duedate() &&
  500:                         $curRes->duedate() > time()) {
  501:                         $color = $hurryUpColor;
  502:                     }
  503:                     if ($color ne "") {
  504:                         $colorizer = "bgcolor=\"$color\"";
  505:                     }
  506:                 }
  507: 
  508:                 if ($curRes->randomout()) {
  509:                     $nonLinkedText .= ' <i>(hidden)</i> ';
  510:                 }
  511: 
  512:                 $rowNum++;
  513:                 my $backgroundColor = $backgroundColors[$rowNum % scalar(@backgroundColors)];
  514: 
  515:                 # FIRST COL: The resource indentation, branch icon, name, and anchor
  516:                 $r->print("  <tr bgcolor=\"$backgroundColor\"><td align=\"left\" valign=\"center\" width=\"60%\">\n");
  517: 
  518:                 # Print the anchor if necessary
  519:                 if ($counter == $currentUrlIndex - $currentUrlDelta) {
  520:                     $r->print('<a name="current" />');
  521:                 }
  522: 
  523:                 # print indentation
  524:                 for (my $i = 0; $i < $indentLevel - $deltalevel + $deltadepth; $i++) {
  525:                     $r->print($indentString);
  526:                 }
  527: 
  528:                 $r->print("  ${newBranchText}${linkopen}$icon${linkclose}\n");
  529: 
  530:                 my $curMarkerBegin = "";
  531:                 my $curMarkerEnd = "";
  532: 
  533:                 # Is this the current resource?
  534:                 if ($curRes->src() eq $currenturl && !$displayedHereMarker) {
  535:                     $curMarkerBegin = '<a name="curloc" /><font color="red" size="+2">&gt; </font>';
  536:                     $curMarkerEnd = '<font color="red" size="+2"> &lt;</font>';
  537:                     $displayedHereMarker = 1;
  538:                 }
  539: 
  540:                 if ($curRes->is_problem() && $part ne "0" && !$condensed) { 
  541:                     $partLabel = " (Part $part)"; 
  542:                     $title = "";
  543:                 }
  544:                 if ($multipart && $condensed) {
  545:                     $nonLinkedText .= ' (' . $curRes->countParts() . ' parts)';
  546:                 }
  547: 
  548:                 $r->print("  $curMarkerBegin<a href=\"$link\">$title$partLabel</a> $curMarkerEnd $nonLinkedText");
  549: 
  550:                 if ($curRes->{RESOURCE_ERROR}) {
  551:                     $r->print(&Apache::loncommon::help_open_topic ("Navmap_Host_Down",
  552:                                               '<font size="-1">Host down</font>'));
  553:                     }
  554: 
  555:                 # SECOND COL: Is there text, feedback, errors??
  556:                 my $discussionHTML = ""; my $feedbackHTML = "";
  557: 
  558:                 if ($curRes->hasDiscussion()) {
  559:                     $discussionHTML = $linkopen .
  560:                         '<img border="0" src="/adm/lonMisc/chat.gif" />' .
  561:                         $linkclose;
  562:                 }
  563: 
  564:                 if ($curRes->getFeedback()) {
  565:                     my $feedback = $curRes->getFeedback();
  566:                     foreach (split(/\,/, $feedback)) {
  567:                         if ($_) {
  568:                             $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
  569:                                 . &Apache::lonnet::escape($_) . '">'
  570:                                 . '<img src="/adm/lonMisc/feedback.gif" '
  571:                                 . 'border="0" /></a>';
  572:                         }
  573:                     }
  574:                 }
  575: 
  576:                 $r->print("<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML&nbsp;</td>");
  577: 
  578:                 # Is this the first displayed part of a multi-part problem
  579:                 # that has not been condensed, so we should suppress these two
  580:                 # columns so we don't display useless status info about part
  581:                 # "0"?
  582:                 my $firstDisplayed = !$condensed && $multipart && $part eq "0";
  583: 
  584:                 # THIRD COL: Problem status icon
  585:                 if ($curRes->is_problem() &&
  586:                     !$firstDisplayed) {
  587:                     my $icon = $statusIconMap{$curRes->status($part)};
  588:                     my $alt = $iconAltTags{$icon};
  589:                     if ($icon) {
  590:                         $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");
  591:                     } else {
  592:                         $r->print("<td width=\"30\">&nbsp;</td>\n");
  593:                     }
  594:                 } else { # not problem, no icon
  595:                     $r->print("<td width=\"30\">&nbsp;</td>\n");
  596:                 }
  597: 
  598:                 # FOURTH COL: Text description
  599:                 $r->print("<td align=\"right\" valign=\"center\">\n");
  600:                 
  601:                 if ($curRes->kind() eq "res" &&
  602:                     $curRes->is_problem() &&
  603:                     !$firstDisplayed) {
  604:                     $r->print ("<font color=\"$color\"><b>") if ($color);
  605:                     $r->print (getDescription($curRes, $part));
  606:                     $r->print ("</b></font>") if ($color);
  607:                 }
  608:                 if ($curRes->is_map() && advancedUser() && $curRes->randompick()) {
  609:                     $r->print('(randomly select ' . $curRes->randompick() .')');
  610:                 }
  611: 
  612:                 $r->print("&nbsp;</td></tr>\n");
  613:             }
  614:         }
  615:         $curRes = $mapIterator->next();
  616:     }
  617: 
  618:     $r->print("</table></body></html>");
  619: 
  620:     $navmap->untieHashes();
  621: 
  622:     return OK;
  623: }
  624: 
  625: # Convenience functions: Returns a string that adds or subtracts
  626: # the second argument from the first hash, appropriate for the 
  627: # query string that determines which folders to recurse on
  628: sub addToFilter {
  629:     my $hashIn = shift;
  630:     my $addition = shift;
  631:     my %hash = %$hashIn;
  632:     $hash{$addition} = 1;
  633: 
  634:     return join (",", keys(%hash));
  635: }
  636: 
  637: sub removeFromFilter {
  638:     my $hashIn = shift;
  639:     my $subtraction = shift;
  640:     my %hash = %$hashIn;
  641: 
  642:     delete $hash{$subtraction};
  643:     return join(",", keys(%hash));
  644: }
  645: 
  646: # Convenience function: Given a stack returned from getStack on the iterator,
  647: # return the correct src() value.
  648: # Later, this should add an anchor when we start putting anchors in pages.
  649: sub getLinkForResource {
  650:     my $stack = shift;
  651:     my $res;
  652: 
  653:     # Check to see if there are any pages in the stack
  654:     foreach $res (@$stack) {
  655:         if (defined($res) && $res->is_page()) {
  656:             return $res->src();
  657:         }
  658:     }
  659: 
  660:     # Failing that, return the src of the last resource that is defined
  661:     # (when we first recurse on a map, it puts an undefined resource
  662:     # on the bottom because $self->{HERE} isn't defined yet, and we
  663:     # want the src for the map anyhow)
  664:     foreach (@$stack) {
  665:         if (defined($_)) { $res = $_; }
  666:     }
  667: 
  668:     return $res->src();
  669: }
  670: 
  671: # Convenience function: This seperates the logic of how to create
  672: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
  673: # etc.) into a seperate function. It takes a resource object as the
  674: # first parameter, and the part number of the resource as the second.
  675: # It's basically a big switch statement on the status of the resource.
  676: 
  677: sub getDescription {
  678:     my $res = shift;
  679:     my $part = shift;
  680:     my $status = $res->status($part);
  681: 
  682:     if ($status == $res->NETWORK_FAILURE) { return ""; }
  683:     if ($status == $res->NOTHING_SET) {
  684:         return "Not currently assigned.";
  685:     }
  686:     if ($status == $res->OPEN_LATER) {
  687:         return "Open " . timeToHumanString($res->opendate($part));
  688:     }
  689:     if ($status == $res->OPEN) {
  690:         if ($res->duedate($part)) {
  691:             return "Due " . timeToHumanString($res->duedate($part));
  692:         } else {
  693:             return "Open, no due date";
  694:         }
  695:     }
  696:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
  697:         return "Answer open " . timeToHumanString($res->answerdate($part));
  698:     }
  699:     if ($status == $res->PAST_DUE_NO_ANSWER) {
  700:         return "Was due " . timeToHumanString($res->duedate($part));
  701:     }
  702:     if ($status == $res->ANSWER_OPEN) {
  703:         return "Answer available";
  704:     }
  705:     if ($status == $res->EXCUSED) {
  706:         return "Excused by instructor";
  707:     }
  708:     if ($status == $res->ATTEMPTED) {
  709:         return "Not yet graded.";
  710:     }
  711:     if ($status == $res->TRIES_LEFT) {
  712:         my $tries = $res->tries($part);
  713:         my $maxtries = $res->maxtries($part);
  714:         my $triesString = "";
  715:         if ($tries && $maxtries) {
  716:             $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
  717:             if ($maxtries > 1 && $maxtries - $tries == 1) {
  718:                 $triesString = "<b>$triesString</b>";
  719:             }
  720:         }
  721:         if ($res->duedate()) {
  722:             return "Due " . timeToHumanString($res->duedate($part)) .
  723:                 " $triesString";
  724:         } else {
  725:             return "No due date $triesString";
  726:         }
  727:     }
  728: }
  729: 
  730: # This puts a human-readable name on the ENV variable.
  731: sub advancedUser {
  732:     return $ENV{'user.adv'};
  733: }
  734: 
  735: 
  736: # timeToHumanString takes a time number and converts it to a
  737: # human-readable representation, meant to be used in the following
  738: # manner:
  739: # print "Due $timestring"
  740: # print "Open $timestring"
  741: # print "Answer available $timestring"
  742: # Very, very, very, VERY English-only... goodness help a localizer on
  743: # this func...
  744: sub timeToHumanString {
  745:     my ($time) = @_;
  746:     # zero, '0' and blank are bad times
  747:     if (!$time) {
  748:         return 'never';
  749:     }
  750: 
  751:     my $now = time();
  752: 
  753:     my @time = localtime($time);
  754:     my @now = localtime($now);
  755: 
  756:     # Positive = future
  757:     my $delta = $time - $now;
  758: 
  759:     my $minute = 60;
  760:     my $hour = 60 * $minute;
  761:     my $day = 24 * $hour;
  762:     my $week = 7 * $day;
  763:     my $inPast = 0;
  764: 
  765:     # Logic in comments:
  766:     # Is it now? (extremely unlikely)
  767:     if ( $delta == 0 ) {
  768:         return "this instant";
  769:     }
  770: 
  771:     if ($delta < 0) {
  772:         $inPast = 1;
  773:         $delta = -$delta;
  774:     }
  775: 
  776:     if ( $delta > 0 ) {
  777: 
  778:         my $tense = $inPast ? " ago" : "";
  779:         my $prefix = $inPast ? "" : "in ";
  780:         
  781:         # Less then a minute
  782:         if ( $delta < $minute ) {
  783:             if ($delta == 1) { return "${prefix}1 second$tense"; }
  784:             return "$prefix$delta seconds$tense";
  785:         }
  786: 
  787:         # Less then an hour
  788:         if ( $delta < $hour ) {
  789:             # If so, use minutes
  790:             my $minutes = floor($delta / 60);
  791:             if ($minutes == 1) { return "${prefix}1 minute$tense"; }
  792:             return "$prefix$minutes minutes$tense";
  793:         }
  794:         
  795:         # Is it less then 24 hours away? If so,
  796:         # display hours + minutes
  797:         if ( $delta < $hour * 24) {
  798:             my $hours = floor($delta / $hour);
  799:             my $minutes = floor(($delta % $hour) / $minute);
  800:             my $hourString = "$hours hours";
  801:             my $minuteString = ", $minutes minutes";
  802:             if ($hours == 1) {
  803:                 $hourString = "1 hour";
  804:             }
  805:             if ($minutes == 1) {
  806:                 $minuteString = ", 1 minute";
  807:             }
  808:             if ($minutes == 0) {
  809:                 $minuteString = "";
  810:             }
  811:             return "$prefix$hourString$minuteString$tense";
  812:         }
  813: 
  814:         # Less then 5 days away, display day of the week and
  815:         # HH:MM
  816:         if ( $delta < $day * 5 ) {
  817:             my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
  818:             $timeStr =~ s/12:00 am/midnight/;
  819:             $timeStr =~ s/12:00 pm/noon/;
  820:             return ($inPast ? "last " : "next ") .
  821:                 $timeStr;
  822:         }
  823:         
  824:         # Is it this year?
  825:         if ( $time[5] == $now[5]) {
  826:             # Return on Month Day, HH:MM meridian
  827:             my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
  828:             $timeStr =~ s/12:00 am/midnight/;
  829:             $timeStr =~ s/12:00 pm/noon/;
  830:             return $timeStr;
  831:         }
  832: 
  833:         # Not this year, so show the year
  834:         my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
  835:         $timeStr =~ s/12:00 am/midnight/;
  836:         $timeStr =~ s/12:00 pm/noon/;
  837:         return $timeStr;
  838:     }
  839: }
  840: 
  841: 1;
  842: 
  843: package Apache::lonnavmaps::navmap;
  844: 
  845: =pod
  846: 
  847: lonnavmaps provides functions and objects for dealing with the compiled course hashes generated when a user enters the course, and also provides the Apache handler for the "Navigation Map" button.
  848: 
  849: =head1 navmap object: Encapsulating the compiled nav map
  850: 
  851: navmap is an object that encapsulates a compiled course map and provides a reasonable interface to it.
  852: 
  853: 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.
  854: 
  855: You must obtain resource objects through the navmap object.
  856: 
  857: =head2 Methods
  858: 
  859: =over 4
  860: 
  861: =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.
  862: 
  863: =item * B<getIterator>(first, finish, filter, condition): See iterator documentation below.
  864: 
  865: =cut
  866: 
  867: use strict;
  868: use GDBM_File;
  869: 
  870: sub new {
  871:     # magic invocation to create a class instance
  872:     my $proto = shift;
  873:     my $class = ref($proto) || $proto;
  874:     my $self = {};
  875: 
  876:     $self->{NAV_HASH_FILE} = shift;
  877:     $self->{PARM_HASH_FILE} = shift;
  878:     $self->{GENERATE_COURSE_USER_OPT} = shift;
  879:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
  880: 
  881:     # Resource cache stores navmap resources as we reference them. We generate
  882:     # them on-demand so we don't pay for creating resources unless we use them.
  883:     $self->{RESOURCE_CACHE} = {};
  884: 
  885:     # Network failure flag, if we accessed the course or user opt and
  886:     # failed
  887:     $self->{NETWORK_FAILURE} = 0;
  888: 
  889:     # tie the nav hash
  890:     my %navmaphash;
  891:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
  892:               &GDBM_READER(), 0640))) {
  893:         return undef;
  894:     }
  895:     $self->{NAV_HASH} = \%navmaphash;
  896:     
  897:     my %parmhash;
  898:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
  899:               &GDBM_READER(), 0640)))
  900:     {
  901:         untie $self->{PARM_HASH};
  902:         return undef;
  903:     }
  904:     $self->{PARM_HASH} = \%parmhash;
  905:     $self->{HASH_TIED} = 1;
  906: 
  907:     bless($self);
  908:         
  909:     return $self;
  910: }
  911: 
  912: sub init {
  913:     my $self = shift;
  914: 
  915:     # If the course opt hash and the user opt hash should be generated,
  916:     # generate them
  917:     if ($self->{GENERATE_COURSE_USER_OPT}) {
  918:         my $uname=$ENV{'user.name'};
  919:         my $udom=$ENV{'user.domain'};
  920:         my $uhome=$ENV{'user.home'};
  921:         my $cid=$ENV{'request.course.id'};
  922:         my $chome=$ENV{'course.'.$cid.'.home'};
  923:         my ($cdom,$cnum)=split(/\_/,$cid);
  924:         
  925:         my $userprefix=$uname.'_'.$udom.'_';
  926:         
  927:         my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
  928:         unless ($uhome eq 'no_host') { 
  929: # ------------------------------------------------- Get coursedata (if present)
  930:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
  931:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
  932:                                                  ':resourcedata',$chome);
  933:                 if ($reply!~/^error\:/) {
  934:                     $courserdatas{$cid}=$reply;
  935:                     $courserdatas{$cid.'.last_cache'}=time;
  936:                 }
  937:                 # check to see if network failed
  938:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
  939:                 {
  940:                     $self->{NETWORK_FAILURE} = 1;
  941:                 }
  942:             }
  943:             foreach (split(/\&/,$courserdatas{$cid})) {
  944:                 my ($name,$value)=split(/\=/,$_);
  945:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
  946:                     &Apache::lonnet::unescape($value);
  947:             }
  948: # --------------------------------------------------- Get userdata (if present)
  949:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
  950:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
  951:                 if ($reply!~/^error\:/) {
  952:                     $userrdatas{$uname.'___'.$udom}=$reply;
  953:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
  954:                 }
  955:                 # check to see if network failed
  956:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
  957:                 {
  958:                     $self->{NETWORK_FAILURE} = 1;
  959:                 }
  960:             }
  961:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
  962:                 my ($name,$value)=split(/\=/,$_);
  963:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
  964:                     &Apache::lonnet::unescape($value);
  965:             }
  966:             $self->{COURSE_OPT} = \%courseopt;
  967:             $self->{USER_OPT} = \%useropt;
  968:         }
  969:     }   
  970: 
  971:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
  972:         my $cid=$ENV{'request.course.id'};
  973:         my ($cdom,$cnum)=split(/\_/,$cid);
  974:         
  975:         my %emailstatus = &Apache::lonnet::dump('email_status');
  976:         my $logoutTime = $emailstatus{'logout'};
  977:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
  978:         $self->{LAST_CHECK} = ($courseLeaveTime > $logoutTime ?
  979:                                $courseLeaveTime : $logoutTime);
  980:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
  981:                                                    $cdom, $cnum);
  982:         my %feedback=();
  983:         my %error=();
  984:         my $keys = &Apache::lonnet::reply('keys:'.
  985:                                           $ENV{'user.domain'}.':'.
  986:                                           $ENV{'user.name'}.':nohist_email',
  987:                                           $ENV{'user.home'});
  988: 
  989:         foreach my $msgid (split(/\&/, $keys)) {
  990:             $msgid=&Apache::lonnet::unescape($msgid);
  991:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
  992:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
  993:                 my ($what,$url)=($1,$2);
  994:                 my %status=
  995:                     &Apache::lonnet::get('email_status',[$msgid]);
  996:                 if ($status{$msgid}=~/^error\:/) { 
  997:                     $status{$msgid}=''; 
  998:                 }
  999:                 
 1000:                 if (($status{$msgid} eq 'new') || 
 1001:                     (!$status{$msgid})) { 
 1002:                     if ($what eq 'Error') {
 1003:                         $error{$url}.=','.$msgid; 
 1004:                     } else {
 1005:                         $feedback{$url}.=','.$msgid;
 1006:                     }
 1007:                 }
 1008:             }
 1009:         }
 1010:         
 1011:         $self->{FEEDBACK} = \%feedback;
 1012:         $self->{ERROR_MSG} = \%error; # what is this? JB
 1013:         $self->{DISCUSSION_TIME} = \%discussiontime;
 1014:         $self->{EMAIL_STATUS} = \%emailstatus;
 1015:         
 1016:     }    
 1017: 
 1018:     $self->{PARM_CACHE} = {};
 1019: }
 1020: 
 1021: # Checks to see if coursemap is defined, matching test in old lonnavmaps
 1022: sub courseMapDefined {
 1023:     my $self = shift;
 1024:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
 1025: 
 1026:     my $firstres = $self->{NAV_HASH}->{"map_start_$uri"};
 1027:     my $lastres = $self->{NAV_HASH}->{"map_finish_$uri"};
 1028:     return $firstres && $lastres;
 1029: }
 1030: 
 1031: sub getIterator {
 1032:     my $self = shift;
 1033:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
 1034:                                                      shift, undef, shift);
 1035:     return $iterator;
 1036: }
 1037: 
 1038: # unties the hash when done
 1039: sub untieHashes {
 1040:     my $self = shift;
 1041:     untie %{$self->{NAV_HASH}} if ($self->{HASH_TIED});
 1042:     untie %{$self->{PARM_HASH}} if ($self->{HASH_TIED});
 1043:     $self->{HASH_TIED} = 0;
 1044: }
 1045: 
 1046: # when the object is destroyed, be sure to untie all the hashes we tied.
 1047: sub DESTROY {
 1048:     my $self = shift;
 1049:     $self->untieHashes();
 1050: }
 1051: 
 1052: # Private function: Does the given resource (as a symb string) have
 1053: # current discussion? Returns 0 if chat/mail data not extracted.
 1054: sub hasDiscussion {
 1055:     my $self = shift;
 1056:     my $symb = shift;
 1057:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
 1058: 
 1059:     return $self->{DISCUSSION_TIME}->{$symb} >
 1060:            $self->{LAST_CHECK};
 1061: }
 1062: 
 1063: # Private function: Does the given resource (as a symb string) have
 1064: # current feedback? Returns the string in the feedback hash, which
 1065: # will be false if it does not exist.
 1066: sub getFeedback { 
 1067:     my $self = shift;
 1068:     my $symb = shift;
 1069: 
 1070:     if (!defined($self->{FEEDBACK})) { return ""; }
 1071:     
 1072:     return $self->{FEEDBACK}->{$symb};
 1073: }
 1074: 
 1075: =pod
 1076: 
 1077: =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.
 1078: 
 1079: =cut
 1080: 
 1081: # The strategy here is to cache the resource objects, and only construct them
 1082: # as we use them. The real point is to prevent reading any more from the tied
 1083: # hash then we have to, which should hopefully alleviate speed problems.
 1084: # Caching is just an incidental detail I throw in because it makes sense.
 1085: 
 1086: sub getById {
 1087:     my $self = shift;
 1088:     my $id = shift;
 1089: 
 1090:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
 1091:     {
 1092:         return $self->{RESOURCE_CACHE}->{$id};
 1093:     }
 1094: 
 1095:     # resource handles inserting itself into cache.
 1096:     return Apache::lonnavmaps::resource->new($self, $id);
 1097: }
 1098: 
 1099: =pod
 1100: 
 1101: =item * B<firstResource>(): Returns a resource object reference corresponding to the first resource in the navmap.
 1102: 
 1103: =cut
 1104: 
 1105: sub firstResource {
 1106:     my $self = shift;
 1107:     my $firstResource = $self->{NAV_HASH}->{'map_start_' .
 1108:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1109:     return $self->getById($firstResource);
 1110: }
 1111: 
 1112: =pod
 1113: 
 1114: =item * B<finishResource>(): Returns a resource object reference corresponding to the last resource in the navmap.
 1115: 
 1116: =cut
 1117: 
 1118: sub finishResource {
 1119:     my $self = shift;
 1120:     my $firstResource = $self->{NAV_HASH}->{'map_finish_' .
 1121:                      &Apache::lonnet::clutter($ENV{'request.course.uri'})};
 1122:     return $self->getById($firstResource);
 1123: }
 1124: 
 1125: # Parmval reads the parm hash and cascades the lookups. parmval_real does
 1126: # the actual lookup; parmval caches the results.
 1127: sub parmval {
 1128:     my $self = shift;
 1129:     my ($what,$symb)=@_;
 1130:     my $hashkey = $what."|||".$symb;
 1131: 
 1132:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
 1133:         return $self->{PARM_CACHE}->{$hashkey};
 1134:     }
 1135: 
 1136:     my $result = $self->parmval_real($what, $symb);
 1137:     $self->{PARM_CACHE}->{$hashkey} = $result;
 1138:     return $result;
 1139: }
 1140: 
 1141: sub parmval_real {
 1142:     my $self = shift;
 1143:     my ($what,$symb) = @_;
 1144: 
 1145:     my $cid=$ENV{'request.course.id'};
 1146:     my $csec=$ENV{'request.course.sec'};
 1147:     my $uname=$ENV{'user.name'};
 1148:     my $udom=$ENV{'user.domain'};
 1149: 
 1150:     unless ($symb) { return ''; }
 1151:     my $result='';
 1152: 
 1153:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1154: 
 1155: # ----------------------------------------------------- Cascading lookup scheme
 1156:     my $rwhat=$what;
 1157:     $what=~s/^parameter\_//;
 1158:     $what=~s/\_/\./;
 1159: 
 1160:     my $symbparm=$symb.'.'.$what;
 1161:     my $mapparm=$mapname.'___(all).'.$what;
 1162:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1163: 
 1164:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
 1165:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
 1166:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
 1167: 
 1168:     my $courselevel= $usercourseprefix.'.'.$what;
 1169:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
 1170:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
 1171: 
 1172:     my $useropt = $self->{USER_OPT};
 1173:     my $courseopt = $self->{COURSE_OPT};
 1174:     my $parmhash = $self->{PARM_HASH};
 1175: 
 1176: # ---------------------------------------------------------- first, check user
 1177:     if ($uname and defined($useropt)) {
 1178:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
 1179:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
 1180:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
 1181:     }
 1182: 
 1183: # ------------------------------------------------------- second, check course
 1184:     if ($csec and defined($courseopt)) {
 1185:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
 1186:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
 1187:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
 1188:     }
 1189: 
 1190:     if (defined($courseopt)) {
 1191:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
 1192:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
 1193:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
 1194:     }
 1195: 
 1196: # ----------------------------------------------------- third, check map parms
 1197: 
 1198:     my $thisparm=$$parmhash{$symbparm};
 1199:     if (defined($thisparm)) { return $thisparm; }
 1200: 
 1201: # ----------------------------------------------------- fourth , check default
 1202: 
 1203:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
 1204:     if (defined($default)) { return $default}
 1205: 
 1206: # --------------------------------------------------- fifth , cascade up parts
 1207: 
 1208:     my ($space,@qualifier)=split(/\./,$rwhat);
 1209:     my $qualifier=join('.',@qualifier);
 1210:     unless ($space eq '0') {
 1211:         my ($part,$id)=split(/\_/,$space);
 1212:         if ($id) {
 1213:             my $partgeneral=$self->parmval($part.".$qualifier",$symb);
 1214:             if (defined($partgeneral)) { return $partgeneral; }
 1215:         } else {
 1216:             my $resourcegeneral=$self->parmval("0.$qualifier",$symb);
 1217:             if (defined($resourcegeneral)) { return $resourcegeneral; }
 1218:         }
 1219:     }
 1220:     return '';
 1221: }
 1222: 
 1223: 
 1224: 1;
 1225: 
 1226: package Apache::lonnavmaps::iterator;
 1227: 
 1228: =pod
 1229: 
 1230: =back
 1231: 
 1232: =head1 navmap Iterator
 1233: 
 1234: 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.
 1235: 
 1236: 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:
 1237: 
 1238: C<my $resourceIterator = $navmap-E<gt>getIterator();>
 1239: 
 1240: To get the next thing from the iterator, call B<next>:
 1241: 
 1242: C<my $nextThing = $resourceIterator-E<gt>next()>
 1243: 
 1244: getIterator behaves as follows:
 1245: 
 1246: =over 4
 1247: 
 1248: =item * B<getIterator>(firstResource, finishResource, filterHash, condition): 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.
 1249: 
 1250: 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.
 1251: 
 1252: 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:
 1253: 
 1254: =over 4
 1255: 
 1256: =item * BEGIN_MAP: A new map is being recursed into. This is returned I<after> the map resource itself is returned.
 1257: 
 1258: =item * END_MAP: The map is now done.
 1259: 
 1260: =item * BEGIN_BRANCH: A branch is now starting. The next resource returned will be the first in that branch.
 1261: 
 1262: =item * END_BRANCH: The branch is now done.
 1263: 
 1264: =back
 1265: 
 1266: The tokens are retreivable via methods on the iterator object, i.e., $iterator->END_MAP.
 1267: 
 1268: =back
 1269: 
 1270: =cut
 1271: 
 1272: # Here are the tokens for the iterator:
 1273: 
 1274: sub BEGIN_MAP { return 1; }    # begining of a new map
 1275: sub END_MAP { return 2; }      # end of the map
 1276: sub BEGIN_BRANCH { return 3; } # beginning of a branch
 1277: sub END_BRANCH { return 4; }   # end of a branch
 1278: sub FORWARD { return 1; }      # go forward
 1279: sub BACKWARD { return 2; }
 1280: 
 1281: sub min {
 1282:     (my $a, my $b) = @_;
 1283:     if ($a < $b) { return $a; } else { return $b; }
 1284: }
 1285: 
 1286: # In the CVS repository, documentation of this algorithm is included 
 1287: # in /doc/lonnavdocs, as a PDF and .tex source. Markers like **1**
 1288: # will reference the same location in the text as the part of the
 1289: # algorithm is running through.
 1290: 
 1291: sub new {
 1292:     # magic invocation to create a class instance
 1293:     my $proto = shift;
 1294:     my $class = ref($proto) || $proto;
 1295:     my $self = {};
 1296: 
 1297:     $self->{NAV_MAP} = shift;
 1298:     return undef unless ($self->{NAV_MAP});
 1299: 
 1300:     # Handle the parameters
 1301:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 1302:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 1303: 
 1304:     # If the given resources are just the ID of the resource, get the
 1305:     # objects
 1306:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 1307:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 1308:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 1309:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 1310: 
 1311:     $self->{FILTER} = shift;
 1312: 
 1313:     # A hash, used as a set, of resource already seen
 1314:     $self->{ALREADY_SEEN} = shift;
 1315:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 1316:     $self->{CONDITION} = shift;
 1317: 
 1318:     # Now, we need to pre-process the map, by walking forward and backward
 1319:     # over the parts of the map we're going to look at.
 1320: 
 1321:     # The processing steps are exactly the same, except for a few small 
 1322:     # changes, so I bundle those up in the following list of two elements:
 1323:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
 1324:     # first_resource).
 1325:     # This prevents writing nearly-identical code twice.
 1326:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
 1327:                         'FIRST_RESOURCE'],
 1328:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
 1329:                         'FINISH_RESOURCE'] );
 1330: 
 1331:     my $maxDepth = 0; # tracks max depth
 1332: 
 1333:     # **1**
 1334: 
 1335:     foreach my $pass (@iterations) {
 1336:         my $direction = $pass->[0];
 1337:         my $valName = $pass->[1];
 1338:         my $nextResourceMethod = $pass->[2];
 1339:         my $firstResourceName = $pass->[3];
 1340: 
 1341:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
 1342:                                                             $self->{FIRST_RESOURCE},
 1343:                                                             $self->{FINISH_RESOURCE},
 1344:                                                             {}, undef, 0, $direction);
 1345:     
 1346:         # prime the recursion
 1347:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
 1348:         my $depth = 0;
 1349:         $iterator->next();
 1350:         my $curRes = $iterator->next();
 1351:         while ($depth > -1) {
 1352:             if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
 1353:             if ($curRes == $iterator->END_MAP()) { $depth--; }
 1354:         
 1355:             if (ref($curRes)) {
 1356:                 my $resultingVal = $curRes->{DATA}->{$valName};
 1357:                 my $nextResources = $curRes->$nextResourceMethod();
 1358:                 my $resourceCount = scalar(@{$nextResources});
 1359: 
 1360:                 if ($resourceCount == 1) { # **3**
 1361:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
 1362:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
 1363:                 }
 1364:                 
 1365:                 if ($resourceCount > 1) { # **4**
 1366:                     foreach my $res (@{$nextResources}) {
 1367:                         my $current = $res->{DATA}->{$valName} || 999999999;
 1368:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
 1369:                     }
 1370:                 }
 1371:             }
 1372:             
 1373:             # Assign the final val (**2**)
 1374:             if (ref($curRes) && $direction == BACKWARD()) {
 1375:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
 1376:                                      $curRes->{DATA}->{BOT_UP_VAL});
 1377:                 
 1378:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
 1379:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
 1380:                 }
 1381:             $curRes = $iterator->next();
 1382:         }
 1383:     }
 1384: 
 1385:     # Set up some bookkeeping information.
 1386:     $self->{CURRENT_DEPTH} = 0;
 1387:     $self->{MAX_DEPTH} = $maxDepth;
 1388:     $self->{STACK} = [];
 1389:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1390: 
 1391:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
 1392:         push @{$self->{STACK}}, [];
 1393:     }
 1394: 
 1395:     # Prime the recursion w/ the first resource **5**
 1396:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
 1397:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
 1398: 
 1399:     bless ($self);
 1400: 
 1401:     return $self;
 1402: }
 1403: 
 1404: sub next {
 1405:     my $self = shift;
 1406: 
 1407:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 1408:         # grab the next from the recursive iterator 
 1409:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 1410: 
 1411:         # is it a begin or end map? If so, update the depth
 1412:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 1413:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 1414: 
 1415:         # Are we back at depth 0? If so, stop recursing
 1416:         if ($self->{RECURSIVE_DEPTH} == 0) {
 1417:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1418:         }
 1419: 
 1420:         return $next;
 1421:     }
 1422: 
 1423:     if (defined($self->{FORCE_NEXT})) {
 1424:         my $tmp = $self->{FORCE_NEXT};
 1425:         $self->{FORCE_NEXT} = undef;
 1426:         return $tmp;
 1427:     }
 1428: 
 1429:     # Have we not yet begun? If not, return BEGIN_MAP and
 1430:     # remember we've started.
 1431:     if ( !$self->{STARTED} ) { 
 1432:         $self->{STARTED} = 1;
 1433:         return $self->BEGIN_MAP();
 1434:     }
 1435: 
 1436:     # Here's the guts of the iterator.
 1437:     
 1438:     # Find the next resource, if any.
 1439:     my $found = 0;
 1440:     my $i = $self->{MAX_DEPTH};
 1441:     my $newDepth;
 1442:     my $here;
 1443:     while ( $i >= 0 && !$found ) {
 1444:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
 1445:             $here = pop @{$self->{STACK}->[$i]}; # **7**
 1446:             $found = 1;
 1447:             $newDepth = $i;
 1448:         }
 1449:         $i--;
 1450:     }
 1451: 
 1452:     # If we still didn't find anything, we're done.
 1453:     if ( !$found ) {
 1454:         # We need to get back down to the correct branch depth
 1455:         if ( $self->{CURRENT_DEPTH} > 0 ) {
 1456:             $self->{CURRENT_DEPTH}--;
 1457:             return END_BRANCH();
 1458:         } else {
 1459:             return END_MAP();
 1460:         }
 1461:     }
 1462: 
 1463:     # If this is not a resource, it must be an END_BRANCH marker we want
 1464:     # to return directly.
 1465:     if (!ref($here)) { # **8**
 1466:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
 1467:             $self->{CURRENT_DEPTH}--;
 1468:             return $here;
 1469:         }
 1470:     }
 1471: 
 1472:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
 1473:     $self->{HERE} = $here;
 1474: 
 1475:     # Get to the right level
 1476:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
 1477:         push @{$self->{STACK}->[$newDepth]}, $here;
 1478:         $self->{CURRENT_DEPTH}--;
 1479:         return END_BRANCH();
 1480:     }
 1481:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
 1482:         push @{$self->{STACK}->[$newDepth]}, $here;
 1483:         $self->{CURRENT_DEPTH}++;
 1484:         return BEGIN_BRANCH();
 1485:     }
 1486: 
 1487:     # If we made it here, we have the next resource, and we're at the
 1488:     # right branch level. So let's examine the resource for where
 1489:     # we can get to from here.
 1490: 
 1491:     # So we need to look at all the resources we can get to from here,
 1492:     # categorize them if we haven't seen them, remember if we have a new
 1493:     my $nextUnfiltered = $here->getNext();
 1494:     my $maxDepthAdded = -1;
 1495:     
 1496:     for (@$nextUnfiltered) {
 1497:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 1498:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
 1499:             push @{$self->{STACK}->[$depth]}, $_;
 1500:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
 1501:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
 1502:         }
 1503:     }
 1504: 
 1505:     # Is this the end of a branch? If so, all of the resources examined above
 1506:     # led to lower levels then the one we are currently at, so we push a END_BRANCH
 1507:     # marker onto the stack so we don't forget.
 1508:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
 1509:     # BC branch and gets to C, it will see F as the only next resource, but it's
 1510:     # one level lower. Thus, this is the end of the branch, since there are no
 1511:     # more resources added to this level or above.
 1512:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
 1513:     if ($isEndOfBranch) { # **9**
 1514:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
 1515:     }
 1516: 
 1517:     # That ends the main iterator logic. Now, do we want to recurse
 1518:     # down this map (if this resource is a map)?
 1519:     if ($self->{HERE}->is_map() &&
 1520:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
 1521:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 1522:         my $firstResource = $self->{HERE}->map_start();
 1523:         my $finishResource = $self->{HERE}->map_finish();
 1524: 
 1525:         $self->{RECURSIVE_ITERATOR} = 
 1526:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
 1527:                                               $finishResource, $self->{FILTER},
 1528:                                               $self->{ALREADY_SEEN}, $self->{CONDITION});
 1529:     }
 1530: 
 1531:     return $self->{HERE};
 1532: 
 1533: }
 1534: 
 1535: =pod
 1536: 
 1537: 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).
 1538: 
 1539: =cut
 1540: 
 1541: sub getStack {
 1542:     my $self=shift;
 1543: 
 1544:     my @stack;
 1545: 
 1546:     $self->populateStack(\@stack);
 1547: 
 1548:     return \@stack;
 1549: }
 1550: 
 1551: # Private method: Calls the iterators recursively to populate the stack.
 1552: sub populateStack {
 1553:     my $self=shift;
 1554:     my $stack = shift;
 1555: 
 1556:     push @$stack, $self->{HERE} if ($self->{HERE});
 1557: 
 1558:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 1559:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
 1560:     }
 1561: }
 1562: 
 1563: 1;
 1564: 
 1565: package Apache::lonnavmaps::DFSiterator;
 1566: 
 1567: # Not documented in the perldoc: This is a simple iterator that just walks
 1568: #  through the nav map and presents the resources in a depth-first search
 1569: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
 1570: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
 1571: #  useful for pre-processing of some kind, and is in fact used by the main
 1572: #  iterator that way, but that's about it.
 1573: # One could imagine merging this into the init routine of the main iterator,
 1574: #  but this might as well be left seperate, since it is possible some other
 1575: #  use might be found for it. - Jeremy
 1576: 
 1577: sub BEGIN_MAP { return 1; }    # begining of a new map
 1578: sub END_MAP { return 2; }      # end of the map
 1579: sub FORWARD { return 1; }      # go forward
 1580: sub BACKWARD { return 2; }
 1581: 
 1582: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
 1583: #         filter hash ref (or undef), already seen hash or undef, condition
 1584: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
 1585: sub new {
 1586:     # magic invocation to create a class instance
 1587:     my $proto = shift;
 1588:     my $class = ref($proto) || $proto;
 1589:     my $self = {};
 1590: 
 1591:     $self->{NAV_MAP} = shift;
 1592:     return undef unless ($self->{NAV_MAP});
 1593: 
 1594:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
 1595:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
 1596: 
 1597:     # If the given resources are just the ID of the resource, get the
 1598:     # objects
 1599:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
 1600:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
 1601:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
 1602:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
 1603: 
 1604:     $self->{FILTER} = shift;
 1605: 
 1606:     # A hash, used as a set, of resource already seen
 1607:     $self->{ALREADY_SEEN} = shift;
 1608:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
 1609:     $self->{CONDITION} = shift;
 1610:     $self->{DIRECTION} = shift || FORWARD();
 1611: 
 1612:     # Flag: Have we started yet?
 1613:     $self->{STARTED} = 0;
 1614: 
 1615:     # Should we continue calling the recursive iterator, if any?
 1616:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1617:     # The recursive iterator, if any
 1618:     $self->{RECURSIVE_ITERATOR} = undef;
 1619:     # Are we recursing on a map, or a branch?
 1620:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
 1621:     # And the count of how deep it is, so that this iterator can keep track of
 1622:     # when to pick back up again.
 1623:     $self->{RECURSIVE_DEPTH} = 0;
 1624: 
 1625:     # For keeping track of our branches, we maintain our own stack
 1626:     $self->{STACK} = [];
 1627: 
 1628:     # Start with the first resource
 1629:     if ($self->{DIRECTION} == FORWARD) {
 1630:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
 1631:     } else {
 1632:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
 1633:     }
 1634: 
 1635:     bless($self);
 1636:     return $self;
 1637: }
 1638: 
 1639: sub next {
 1640:     my $self = shift;
 1641:     
 1642:     # Are we using a recursive iterator? If so, pull from that and
 1643:     # watch the depth; we want to resume our level at the correct time.
 1644:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
 1645:         # grab the next from the recursive iterator
 1646:         my $next = $self->{RECURSIVE_ITERATOR}->next();
 1647:         
 1648:         # is it a begin or end map? Update depth if so
 1649:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
 1650:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
 1651: 
 1652:         # Are we back at depth 0? If so, stop recursing.
 1653:         if ($self->{RECURSIVE_DEPTH} == 0) {
 1654:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
 1655:         }
 1656:         
 1657:         return $next;
 1658:     }
 1659: 
 1660:     # Is there a current resource to grab? If not, then return
 1661:     # END_MAP, which will end the iterator.
 1662:     if (scalar(@{$self->{STACK}}) == 0) {
 1663:         return $self->END_MAP();
 1664:     }
 1665: 
 1666:     # Have we not yet begun? If not, return BEGIN_MAP and 
 1667:     # remember that we've started.
 1668:     if ( !$self->{STARTED} ) {
 1669:         $self->{STARTED} = 1;
 1670:         return $self->BEGIN_MAP;
 1671:     }
 1672: 
 1673:     # Get the next resource in the branch
 1674:     $self->{HERE} = pop @{$self->{STACK}};
 1675: 
 1676:     # remember that we've seen this, so we don't return it again later
 1677:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
 1678:     
 1679:     # Get the next possible resources
 1680:     my $nextUnfiltered;
 1681:     if ($self->{DIRECTION} == FORWARD()) {
 1682:         $nextUnfiltered = $self->{HERE}->getNext();
 1683:     } else {
 1684:         $nextUnfiltered = $self->{HERE}->getPrevious();
 1685:     }
 1686:     my $next = [];
 1687: 
 1688:     # filter the next possibilities to remove things we've 
 1689:     # already seen.
 1690:     foreach (@$nextUnfiltered) {
 1691:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
 1692:             push @$next, $_;
 1693:         }
 1694:     }
 1695: 
 1696:     while (@$next) {
 1697:         # copy the next possibilities over to the stack
 1698:         push @{$self->{STACK}}, shift @$next;
 1699:     }
 1700: 
 1701:     # If this is a map and we want to recurse down it... (not filtered out)
 1702:     if ($self->{HERE}->is_map() && 
 1703:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
 1704:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
 1705:         my $firstResource = $self->{HERE}->map_start();
 1706:         my $finishResource = $self->{HERE}->map_finish();
 1707: 
 1708:         $self->{RECURSIVE_ITERATOR} =
 1709:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
 1710:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
 1711:                                              $self->{CONDITION}, $self->{DIRECTION});
 1712:     }
 1713: 
 1714:     return $self->{HERE};
 1715: }
 1716: 
 1717: 1;
 1718: 
 1719: package Apache::lonnavmaps::resource;
 1720: 
 1721: use Apache::lonnet;
 1722: 
 1723: =pod
 1724: 
 1725: =head1 Object: resource
 1726: 
 1727: 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.
 1728: 
 1729: A resource only makes sense in the context of a navmap, as some of the data is stored in the navmap object.
 1730: 
 1731: You will probably never need to instantiate this object directly. Use Apache::lonnavmap::navmap, and use the "start" method to obtain the starting resource.
 1732: 
 1733: =head2 Public Members
 1734: 
 1735: 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.
 1736: 
 1737: =head2 Methods
 1738: 
 1739: =over 4
 1740: 
 1741: =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.
 1742: 
 1743: =back
 1744: 
 1745: =cut
 1746: 
 1747: sub new {
 1748:     # magic invocation to create a class instance
 1749:     my $proto = shift;
 1750:     my $class = ref($proto) || $proto;
 1751:     my $self = {};
 1752: 
 1753:     $self->{NAV_MAP} = shift;
 1754:     $self->{ID} = shift;
 1755: 
 1756:     # Store this new resource in the parent nav map's cache.
 1757:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
 1758:     $self->{RESOURCE_ERROR} = 0;
 1759: 
 1760:     # A hash that can be used by two-pass algorithms to store data
 1761:     # about this resource in. Not used by the resource object
 1762:     # directly.
 1763:     $self->{DATA} = {};
 1764:    
 1765:     bless($self);
 1766:     
 1767:     return $self;
 1768: }
 1769: 
 1770: # private function: simplify the NAV_HASH lookups we keep doing
 1771: # pass the name, and to automatically append my ID, pass a true val on the
 1772: # second param
 1773: sub navHash {
 1774:     my $self = shift;
 1775:     my $param = shift;
 1776:     my $id = shift;
 1777:     return $self->{NAV_MAP}->{NAV_HASH}->{$param . ($id?$self->{ID}:"")};
 1778: }
 1779: 
 1780: =pod
 1781: 
 1782: B<Metadata Retreival>
 1783: 
 1784: These are methods that help you retrieve metadata about the resource: Method names are based on the fields in the compiled course representation.
 1785: 
 1786: =over 4
 1787: 
 1788: =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").
 1789: 
 1790: =item * B<ext>: Returns true if the resource is external.
 1791: 
 1792: =item * B<goesto>: Returns the "goesto" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
 1793: 
 1794: =item * B<kind>: Returns the kind of the resource from the compiled nav map.
 1795: 
 1796: =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.
 1797: 
 1798: =item * B<randompick>: Returns true for a map if the randompick feature is being used on the map. (?)
 1799: 
 1800: =item * B<src>: Returns the source for the resource.
 1801: 
 1802: =item * B<symb>: Returns the symb for the resource.
 1803: 
 1804: =item * B<title>: Returns the title of the resource.
 1805: 
 1806: =item * B<to>: Returns the "to" value from the compiled nav map. (It is likely you want to use B<getNext> instead.)
 1807: 
 1808: =back
 1809: 
 1810: =cut
 1811: 
 1812: # These info functions can be used directly, as they don't return
 1813: # resource information.
 1814: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
 1815: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
 1816: sub from { my $self=shift; return $self->navHash("from_", 1); }
 1817: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
 1818: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
 1819: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
 1820: sub randompick { 
 1821:     my $self = shift;
 1822:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
 1823:                                                '.0.parameter_randompick'};
 1824: }
 1825: sub src { 
 1826:     my $self=shift;
 1827:     return $self->navHash("src_", 1);
 1828: }
 1829: sub symb {
 1830:     my $self=shift;
 1831:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
 1832:     my $symbSrc = &Apache::lonnet::declutter($self->src());
 1833:     return &Apache::lonnet::declutter(
 1834:          $self->navHash('map_id_'.$first)) 
 1835:         . '___' . $second . '___' . $symbSrc;
 1836: }
 1837: sub title { my $self=shift; return $self->navHash("title_", 1); }
 1838: sub to { my $self=shift; return $self->navHash("to_", 1); }
 1839: sub compTitle {
 1840:     my $self = shift;
 1841:     my $title = $self->title();
 1842:     if (!$title) {
 1843:         $title = $self->src();
 1844:         $title = substr($title, rindex($title, '/') + 1);
 1845:     }
 1846:     return $title;
 1847: }
 1848: =pod
 1849: 
 1850: B<Predicate Testing the Resource>
 1851: 
 1852: These methods are shortcuts to deciding if a given resource has a given property.
 1853: 
 1854: =over 4
 1855: 
 1856: =item * B<is_map>: Returns true if the resource is a map type.
 1857: 
 1858: =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.)
 1859: 
 1860: =item * B<is_page>: Returns true if the resource is a page.
 1861: 
 1862: =item * B<is_problem>: Returns true if the resource is a problem.
 1863: 
 1864: =item * B<is_sequence>: Returns true if the resource is a sequence.
 1865: 
 1866: =back
 1867: 
 1868: =cut
 1869: 
 1870: 
 1871: sub is_html {
 1872:     my $self=shift;
 1873:     my $src = $self->src();
 1874:     return ($src =~ /html$/);
 1875: }
 1876: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
 1877: sub is_page {
 1878:     my $self=shift;
 1879:     my $src = $self->src();
 1880:     return ($src =~ /page$/);
 1881: }
 1882: sub is_problem {
 1883:     my $self=shift;
 1884:     my $src = $self->src();
 1885:     return ($src =~ /problem$/);
 1886: }
 1887: sub is_sequence {
 1888:     my $self=shift;
 1889:     my $src = $self->src();
 1890:     return ($src =~ /sequence$/);
 1891: }
 1892: 
 1893: # Private method: Shells out to the parmval in the nav map, handler parts.
 1894: sub parmval {
 1895:     my $self = shift;
 1896:     my $what = shift;
 1897:     my $part = shift || "0";
 1898:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
 1899: }
 1900: 
 1901: =pod
 1902: 
 1903: B<Map Methods>
 1904: 
 1905: These methods are useful for getting information about the map properties of the resource, if the resource is a map (B<is_map>).
 1906: 
 1907: =over 4
 1908: 
 1909: =item * B<map_finish>: Returns a reference to a resource object corresponding to the finish resource of the map.
 1910: 
 1911: =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.
 1912: 
 1913: =item * B<map_start>: Returns a reference to a resource object corresponding to the start resource of the map.
 1914: 
 1915: =item * B<map_type>: Returns a string with the type of the map in it.
 1916: 
 1917: =back
 1918: 
 1919: =cut
 1920: 
 1921: sub map_finish {
 1922:     my $self = shift;
 1923:     my $src = $self->src();
 1924:     my $res = $self->navHash("map_finish_$src", 0);
 1925:     $res = $self->{NAV_MAP}->getById($res);
 1926:     return $res;
 1927: }
 1928: sub map_pc {
 1929:     my $self = shift;
 1930:     my $src = $self->src();
 1931:     return $self->navHash("map_pc_$src", 0);
 1932: }
 1933: sub map_start {
 1934:     my $self = shift;
 1935:     my $src = $self->src();
 1936:     my $res = $self->navHash("map_start_$src", 0);
 1937:     $res = $self->{NAV_MAP}->getById($res);
 1938:     return $res;
 1939: }
 1940: sub map_type {
 1941:     my $self = shift;
 1942:     my $pc = $self->map_pc();
 1943:     return $self->navHash("map_type_$pc", 0);
 1944: }
 1945: 
 1946: 
 1947: 
 1948: #####
 1949: # Property queries
 1950: #####
 1951: 
 1952: # These functions will be responsible for returning the CORRECT
 1953: # VALUE for the parameter, no matter what. So while they may look
 1954: # like direct calls to parmval, they can be more then that.
 1955: # So, for instance, the duedate function should use the "duedatetype"
 1956: # information, rather then the resource object user.
 1957: 
 1958: =pod
 1959: 
 1960: =head2 Resource Parameters
 1961: 
 1962: 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.
 1963: 
 1964: 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.)
 1965: 
 1966: =over 4
 1967: 
 1968: =item * B<acc>: Get the Client IP/Name Access Control information.
 1969: 
 1970: =item * B<answerdate>: Get the answer-reveal date for the problem.
 1971: 
 1972: =item * B<duedate>: Get the due date for the problem.
 1973: 
 1974: =item * B<tries>: Get the number of tries the student has used on the problem.
 1975: 
 1976: =item * B<maxtries>: Get the number of max tries allowed.
 1977: 
 1978: =item * B<opendate>: Get the open date for the problem.
 1979: 
 1980: =item * B<sig>: Get the significant figures setting.
 1981: 
 1982: =item * B<tol>: Get the tolerance for the problem.
 1983: 
 1984: =item * B<tries>: Get the number of tries the user has already used on the problem.
 1985: 
 1986: =item * B<type>: Get the question type for the problem.
 1987: 
 1988: =item * B<weight>: Get the weight for the problem.
 1989: 
 1990: =back
 1991: 
 1992: =cut
 1993: 
 1994: sub acc {
 1995:     (my $self, my $part) = @_;
 1996:     return $self->parmval("acc", $part);
 1997: }
 1998: sub answerdate {
 1999:     (my $self, my $part) = @_;
 2000:     # Handle intervals
 2001:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
 2002:         return $self->duedate($part) + 
 2003:             $self->parmval("answerdate", $part);
 2004:     }
 2005:     return $self->parmval("answerdate", $part);
 2006: }
 2007: sub awarded { my $self = shift; return $self->queryRestoreHash('awarded', shift); }
 2008: sub duedate {
 2009:     (my $self, my $part) = @_;
 2010:     return $self->parmval("duedate", $part);
 2011: }
 2012: sub maxtries {
 2013:     (my $self, my $part) = @_;
 2014:     return $self->parmval("maxtries", $part);
 2015: }
 2016: sub opendate {
 2017:     (my $self, my $part) = @_;
 2018:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
 2019:         return $self->duedate($part) -
 2020:             $self->parmval("opendate", $part);
 2021:     }
 2022:     return $self->parmval("opendate");
 2023: }
 2024: sub sig {
 2025:     (my $self, my $part) = @_;
 2026:     return $self->parmval("sig", $part);
 2027: }
 2028: sub tol {
 2029:     (my $self, my $part) = @_;
 2030:     return $self->parmval("tol", $part);
 2031: }
 2032: sub tries { 
 2033:     my $self = shift; 
 2034:     my $tries = $self->queryRestoreHash('tries', shift);
 2035:     if (!defined($tries)) { return '0';}
 2036:     return $tries;
 2037: }
 2038: sub type {
 2039:     (my $self, my $part) = @_;
 2040:     return $self->parmval("type", $part);
 2041: }
 2042: sub weight { 
 2043:     my $self = shift; my $part = shift;
 2044:     return $self->parmval("weight", $part);
 2045: }
 2046: 
 2047: # Multiple things need this
 2048: sub getReturnHash {
 2049:     my $self = shift;
 2050:     
 2051:     if (!defined($self->{RETURN_HASH})) {
 2052:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
 2053:         $self->{RETURN_HASH} = \%tmpHash;
 2054:     }
 2055: }       
 2056: 
 2057: ######
 2058: # Status queries
 2059: ######
 2060: 
 2061: # These methods query the status of problems.
 2062: 
 2063: # If we need to count parts, this function determines the number of
 2064: # parts from the metadata. When called, it returns a reference to a list
 2065: # of strings corresponding to the parts. (Thus, using it in a scalar context
 2066: # tells you how many parts you have in the problem:
 2067: # $partcount = scalar($resource->countParts());
 2068: # Don't use $self->{PARTS} directly because you don't know if it's been
 2069: # computed yet.
 2070: 
 2071: =pod
 2072: 
 2073: =head2 Resource misc
 2074: 
 2075: Misc. functions for the resource.
 2076: 
 2077: =over 4
 2078: 
 2079: =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.
 2080: 
 2081: =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:
 2082: 
 2083:  for (split(/\,/, $res->getFeedback())) {
 2084:     my $link = &Apache::lonnet::escape($_);
 2085:     ...
 2086: 
 2087: and use the link as appropriate.
 2088: 
 2089: =cut
 2090: 
 2091: sub hasDiscussion {
 2092:     my $self = shift;
 2093:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
 2094: }
 2095: 
 2096: sub getFeedback {
 2097:     my $self = shift;
 2098:     return $self->{NAV_MAP}->getFeedback($self->src());
 2099: }
 2100: 
 2101: =pod
 2102: 
 2103: =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.)
 2104: 
 2105: =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.
 2106: 
 2107: =back
 2108: 
 2109: =cut
 2110: 
 2111: sub parts {
 2112:     my $self = shift;
 2113: 
 2114:     if ($self->ext) { return ['0']; }
 2115: 
 2116:     $self->extractParts();
 2117:     return $self->{PARTS};
 2118: }
 2119: 
 2120: sub countParts {
 2121:     my $self = shift;
 2122:     
 2123:     my $parts = $self->parts();
 2124: 
 2125:     if ($self->{RESOURCE_ERROR}) {
 2126:         return 0;
 2127:     }
 2128: 
 2129:     if (scalar(@{$parts}) < 2) { return 1;}
 2130: 
 2131:     return scalar(@{$parts}) - 1;
 2132: }
 2133: 
 2134: # Private function: Extracts the parts information and saves it
 2135: sub extractParts { 
 2136:     my $self = shift;
 2137:     
 2138:     return if ($self->{PARTS});
 2139:     return if ($self->ext);
 2140: 
 2141:     $self->{PARTS} = [];
 2142: 
 2143:     # Retrieve part count, if this is a problem
 2144:     if ($self->is_problem()) {
 2145:         my $metadata = &Apache::lonnet::metadata($self->src(), 'allpossiblekeys');
 2146:         if (!$metadata) {
 2147:             $self->{RESOURCE_ERROR} = 1;
 2148:             $self->{PARTS} = [];
 2149:             return;
 2150:         }
 2151:         
 2152:         foreach (split(/\,/,$metadata)) {
 2153:             if ($_ =~ /^parameter\_(.*)\_opendate$/) {
 2154:                 push @{$self->{PARTS}}, $1;
 2155:             }
 2156:         }
 2157:         
 2158:         
 2159:         # Is this possible to do in one line? - Jeremy
 2160:         my @sortedParts = sort @{$self->{PARTS}};
 2161:         $self->{PARTS} = \@sortedParts;
 2162:     }
 2163: 
 2164:     return;
 2165: }
 2166: 
 2167: =pod
 2168: 
 2169: =head2 Resource Status
 2170: 
 2171: Problem resources have status information, reflecting their various dates and completion statuses. 
 2172: 
 2173: There are two aspects to the status: the date-related information and the completion information.
 2174: 
 2175: Idiomatic usage of these two methods would probably look something like
 2176: 
 2177:  foreach ($resource->parts()) {
 2178:     my $dateStatus = $resource->getDateStatus($_);
 2179:     my $completionStatus = $resource->getCompletionStatus($_);
 2180: 
 2181:     or
 2182: 
 2183:     my $status = $resource->status($_);
 2184: 
 2185:     ... use it here ...
 2186:  }
 2187: 
 2188: 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.
 2189: 
 2190: The symbolic constants shown below can be accessed through the resource object: $res->OPEN.
 2191: 
 2192: =over 4
 2193: 
 2194: =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:
 2195: 
 2196: =back
 2197: 
 2198: B<Date Codes>
 2199: 
 2200: =over 4
 2201: 
 2202: =item * B<OPEN_LATER>: The problem will be opened later.
 2203: 
 2204: =item * B<OPEN>: Open and not yet due.
 2205: 
 2206: 
 2207: =item * B<PAST_DUE_ANSWER_LATER>: The due date has passed, but the answer date has not yet arrived.
 2208: 
 2209: =item * B<PAST_DUE_NO_ANSWER>: The due date has passed and there is no answer opening date set.
 2210: 
 2211: =item * B<ANSWER_OPEN>: The answer date is here.
 2212: 
 2213: =item * B<NETWORK_FAILURE>: The information is unknown due to network failure.
 2214: 
 2215: =back
 2216: 
 2217: =cut
 2218: 
 2219: # Apparently the compiler optimizes these into constants automatically
 2220: sub OPEN_LATER             { return 0; }
 2221: sub OPEN                   { return 1; }
 2222: sub PAST_DUE_NO_ANSWER     { return 2; }
 2223: sub PAST_DUE_ANSWER_LATER  { return 3; }
 2224: sub ANSWER_OPEN            { return 4; }
 2225: sub NOTHING_SET            { return 5; } 
 2226: sub NETWORK_FAILURE        { return 100; }
 2227: 
 2228: # getDateStatus gets the date status for a given problem part. 
 2229: # Because answer date, due date, and open date are fully independent
 2230: # (i.e., it is perfectly possible to *only* have an answer date), 
 2231: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
 2232: # (past, future, none given). This function handles this with a decision
 2233: # tree. Read the comments to follow the decision tree.
 2234: 
 2235: sub getDateStatus {
 2236:     my $self = shift;
 2237:     my $part = shift;
 2238:     $part = "0" if (!defined($part));
 2239: 
 2240:     # Always return network failure if there was one.
 2241:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2242: 
 2243:     my $now = time();
 2244: 
 2245:     my $open = $self->opendate($part);
 2246:     my $due = $self->duedate($part);
 2247:     my $answer = $self->answerdate($part);
 2248: 
 2249:     if (!$open && !$due && !$answer) {
 2250:         # no data on the problem at all
 2251:         # should this be the same as "open later"? think multipart.
 2252:         return $self->NOTHING_SET;
 2253:     }
 2254:     if (!$open || $now < $open) {return $self->OPEN_LATER}
 2255:     if (!$due || $now < $due) {return $self->OPEN}
 2256:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
 2257:     if ($answer) { return $self->ANSWER_OPEN; }
 2258:     return PAST_DUE_NO_ANSWER;
 2259: }
 2260: 
 2261: =pod
 2262: 
 2263: B<>
 2264: 
 2265: =over 4
 2266: 
 2267: =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:
 2268: 
 2269: =back 
 2270: 
 2271: B<Completion Codes>
 2272: 
 2273: =over 4
 2274: 
 2275: =item * B<NOT_ATTEMPTED>: Has not been attempted at all.
 2276: 
 2277: =item * B<INCORRECT>: Attempted, but wrong by student.
 2278: 
 2279: =item * B<INCORRECT_BY_OVERRIDE>: Attempted, but wrong by instructor override.
 2280: 
 2281: =item * B<CORRECT>: Correct or correct by instructor.
 2282: 
 2283: =item * B<CORRECT_BY_OVERRIDE>: Correct by instructor override.
 2284: 
 2285: =item * B<EXCUSED>: Excused. Not yet implemented.
 2286: 
 2287: =item * B<NETWORK_FAILURE>: Information not available due to network failure.
 2288: 
 2289: =item * B<ATTEMPTED>: Attempted, and not yet graded.
 2290: 
 2291: =back
 2292: 
 2293: =cut
 2294: 
 2295: sub NOT_ATTEMPTED         { return 10; }
 2296: sub INCORRECT             { return 11; }
 2297: sub INCORRECT_BY_OVERRIDE { return 12; }
 2298: sub CORRECT               { return 13; }
 2299: sub CORRECT_BY_OVERRIDE   { return 14; }
 2300: sub EXCUSED               { return 15; }
 2301: sub ATTEMPTED             { return 16; }
 2302: 
 2303: sub getCompletionStatus {
 2304:     my $self = shift;
 2305:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2306: 
 2307:     my $status = $self->queryRestoreHash('solved', shift);
 2308: 
 2309:     # Left as seperate if statements in case we ever do more with this
 2310:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
 2311:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
 2312:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
 2313:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
 2314:     if ($status eq 'excused') {return $self->EXCUSED; }
 2315:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
 2316:     return $self->NOT_ATTEMPTED;
 2317: }
 2318: 
 2319: sub queryRestoreHash {
 2320:     my $self = shift;
 2321:     my $hashentry = shift;
 2322:     my $part = shift;
 2323:     $part = "0" if (!defined($part));
 2324:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
 2325: 
 2326:     $self->getReturnHash();
 2327: 
 2328:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
 2329: }
 2330: 
 2331: =pod
 2332: 
 2333: B<Composite Status>
 2334: 
 2335: 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):
 2336: 
 2337: =over 4
 2338: 
 2339: =item * B<NETWORK_FAILURE>: The network has failed and the information is not available.
 2340: 
 2341: =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".)
 2342: 
 2343: =item * B<CORRECT>: For any reason at all, the part is considered correct.
 2344: 
 2345: =item * B<EXCUSED>: For any reason at all, the problem is excused.
 2346: 
 2347: =item * B<PAST_DUE_NO_ANSWER>: The problem is past due, not considered correct, and no answer date is set.
 2348: 
 2349: =item * B<PAST_DUE_ANSWER_LATER>: The problem is past due, not considered correct, and an answer date in the future is set.
 2350: 
 2351: =item * B<ANSWER_OPEN>: The problem is past due, not correct, and the answer is now available.
 2352: 
 2353: =item * B<OPEN_LATER>: The problem is not yet open.
 2354: 
 2355: =item * B<TRIES_LEFT>: The problem is open, has been tried, is not correct, but there are tries left.
 2356: 
 2357: =item * B<INCORRECT>: The problem is open, and all tries have been used without getting the correct answer.
 2358: 
 2359: =item * B<OPEN>: The item is open and not yet tried.
 2360: 
 2361: =item * B<ATTEMPTED>: The problem has been attempted.
 2362: 
 2363: =back
 2364: 
 2365: =cut
 2366: 
 2367: sub TRIES_LEFT { return 10; }
 2368: 
 2369: sub status {
 2370:     my $self = shift;
 2371:     my $part = shift;
 2372:     if (!defined($part)) { $part = "0"; }
 2373:     my $completionStatus = $self->getCompletionStatus($part);
 2374:     my $dateStatus = $self->getDateStatus($part);
 2375: 
 2376:     # What we have is a two-dimensional matrix with 4 entries on one
 2377:     # dimension and 5 entries on the other, which we want to colorize,
 2378:     # plus network failure and "no date data at all".
 2379: 
 2380:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
 2381: 
 2382:     # There are a few whole rows we can dispose of:
 2383:     if ($completionStatus == CORRECT ||
 2384:         $completionStatus == CORRECT_BY_OVERRIDE ) {
 2385:         return CORRECT; 
 2386:     }
 2387: 
 2388:     if ($completionStatus == ATTEMPTED) {
 2389:         return ATTEMPTED;
 2390:     }
 2391: 
 2392:     # If it's EXCUSED, then return that no matter what
 2393:     if ($completionStatus == EXCUSED) {
 2394:         return EXCUSED; 
 2395:     }
 2396: 
 2397:     if ($dateStatus == NOTHING_SET) {
 2398:         return NOTHING_SET;
 2399:     }
 2400: 
 2401:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
 2402:     # by 4 matrix (date statuses).
 2403: 
 2404:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
 2405:         $dateStatus == PAST_DUE_NO_ANSWER ) {
 2406:         return $dateStatus; 
 2407:     }
 2408: 
 2409:     if ($dateStatus == ANSWER_OPEN) {
 2410:         return ANSWER_OPEN;
 2411:     }
 2412: 
 2413:     # Now: (incorrect, incorrect_override, not_attempted) x 
 2414:     # (open_later), (open)
 2415:     
 2416:     if ($dateStatus == OPEN_LATER) {
 2417:         return OPEN_LATER;
 2418:     }
 2419: 
 2420:     # If it's WRONG...
 2421:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
 2422:         # and there are TRIES LEFT:
 2423:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
 2424:             return TRIES_LEFT;
 2425:         }
 2426:         return INCORRECT; # otherwise, return orange; student can't fix this
 2427:     }
 2428: 
 2429:     # Otherwise, it's untried and open
 2430:     return OPEN; 
 2431: }
 2432: 
 2433: =pod
 2434: 
 2435: =head2 Resource/Nav Map Navigation
 2436: 
 2437: =over 4
 2438: 
 2439: =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. 
 2440: 
 2441: =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. 
 2442: 
 2443: =cut
 2444: 
 2445: sub getNext {
 2446:     my $self = shift;
 2447:     my @branches;
 2448:     my $to = $self->to();
 2449:     foreach my $branch ( split(/,/, $to) ) {
 2450:         my $choice = $self->{NAV_MAP}->getById($branch);
 2451:         my $next = $choice->goesto();
 2452:         $next = $self->{NAV_MAP}->getById($next);
 2453: 
 2454:         # Don't remember it if the student doesn't have browse priviledges
 2455:         # future note: this may properly belong in the client of the resource
 2456:         my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
 2457:         if (!($browsePriv ne '2' && $browsePriv ne 'F')) {
 2458:             push @branches, $next;
 2459:         }
 2460:     }
 2461:     return \@branches;
 2462: }
 2463: 
 2464: sub getPrevious {
 2465:     my $self = shift;
 2466:     my @branches;
 2467:     my $from = $self->from();
 2468:     foreach my $branch ( split /,/, $from) {
 2469:         my $choice = $self->{NAV_MAP}->getById($branch);
 2470:         my $prev = $choice->comesfrom();
 2471:         $prev = $self->{NAV_MAP}->getById($prev);
 2472: 
 2473:         # Don't remember it if the student doesn't have browse priviledges
 2474:         # future note: this may properly belong in the client of the resource
 2475:         my $browsePriv = &Apache::lonnet::allowed('bre', $self->src);
 2476:         if (!($browsePriv ne '2' && $browsePriv ne 'F')) {
 2477:             push @branches, $prev;
 2478:         }
 2479:     }
 2480:     return \@branches;
 2481: }
 2482: 
 2483: =pod
 2484: 
 2485: =back
 2486: 
 2487: =cut
 2488: 
 2489: 1;
 2490: 
 2491: __END__
 2492: 
 2493: 

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