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

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

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