File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.103: download - view: text, annotated - select for diffs
Tue Nov 12 18:25:11 2002 UTC (21 years, 6 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Oh, and I should add this one too.

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

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