File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.116: download - view: text, annotated - select for diffs
Tue Nov 26 16:25:36 2002 UTC (21 years, 6 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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