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

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

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