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

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

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