File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.131: download - view: text, annotated - select for diffs
Tue Jan 28 22:25:54 2003 UTC (21 years, 3 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Fixes that hidden problems for random out aborts the map.

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

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