Annotation of loncom/interface/lonnavmaps.pm, revision 1.129

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

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