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

1.2       www         1: # The LearningOnline Network with CAPA
                      2: # Navigate Maps Handler
1.1       www         3: #
1.205   ! bowersj2    4: # $Id: lonnavmaps.pm,v 1.204 2003/06/14 00:11:12 albertel Exp $
1.20      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.2       www        28: # (Page Handler
1.1       www        29: #
1.2       www        30: # (TeX Content Handler
1.1       www        31: #
1.2       www        32: # 05/29/00,05/30 Gerd Kortemeyer)
                     33: # 08/30,08/31,09/06,09/14,09/15,09/16,09/19,09/20,09/21,09/23,
                     34: # 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        35: #
1.17      www        36: # 3/1/1,6/1,17/1,29/1,30/1,2/8,9/21,9/24,9/25 Gerd Kortemeyer
1.21      www        37: # YEAR=2002
                     38: # 1/1 Gerd Kortemeyer
1.105     bowersj2   39: # Oct-Nov Jeremy Bowers
1.153     bowersj2   40: # YEAR=2003
                     41: # Jeremy Bowers ... lots of days
1.2       www        42: 
1.1       www        43: package Apache::lonnavmaps;
                     44: 
                     45: use strict;
1.2       www        46: use Apache::Constants qw(:common :http);
1.18      albertel   47: use Apache::loncommon();
1.150     www        48: use Apache::lonmenu();
1.73      bowersj2   49: use POSIX qw (floor strftime);
1.192     bowersj2   50: use Data::Dumper; # for debugging, not always used
1.2       www        51: 
1.133     bowersj2   52: # symbolic constants
                     53: sub SYMB { return 1; }
                     54: sub URL { return 2; }
                     55: sub NOTHING { return 3; }
                     56: 
                     57: # Some data
                     58: 
1.140     bowersj2   59: my $resObj = "Apache::lonnavmaps::resource";
                     60: 
1.135     bowersj2   61: # Keep these mappings in sync with lonquickgrades, which uses the colors
                     62: # instead of the icons.
                     63: my %statusIconMap = 
1.140     bowersj2   64:     ( $resObj->NETWORK_FAILURE    => '',
                     65:       $resObj->NOTHING_SET        => '',
                     66:       $resObj->CORRECT            => 'navmap.correct.gif',
                     67:       $resObj->EXCUSED            => 'navmap.correct.gif',
                     68:       $resObj->PAST_DUE_NO_ANSWER => 'navmap.wrong.gif',
                     69:       $resObj->PAST_DUE_ANSWER_LATER => 'navmap.wrong.gif',
                     70:       $resObj->ANSWER_OPEN        => 'navmap.wrong.gif',
                     71:       $resObj->OPEN_LATER         => '',
                     72:       $resObj->TRIES_LEFT         => 'navmap.open.gif',
                     73:       $resObj->INCORRECT          => 'navmap.wrong.gif',
                     74:       $resObj->OPEN               => 'navmap.open.gif',
1.200     bowersj2   75:       $resObj->ATTEMPTED          => 'navmap.ellipsis.gif',
1.185     bowersj2   76:       $resObj->ANSWER_SUBMITTED   => '' );
1.135     bowersj2   77: 
                     78: my %iconAltTags = 
                     79:     ( 'navmap.correct.gif' => 'Correct',
                     80:       'navmap.wrong.gif'   => 'Incorrect',
                     81:       'navmap.open.gif'    => 'Open' );
1.133     bowersj2   82: 
1.136     bowersj2   83: # Defines a status->color mapping, null string means don't color
                     84: my %colormap = 
1.140     bowersj2   85:     ( $resObj->NETWORK_FAILURE        => '',
                     86:       $resObj->CORRECT                => '',
                     87:       $resObj->EXCUSED                => '#3333FF',
                     88:       $resObj->PAST_DUE_ANSWER_LATER  => '',
                     89:       $resObj->PAST_DUE_NO_ANSWER     => '',
                     90:       $resObj->ANSWER_OPEN            => '#006600',
                     91:       $resObj->OPEN_LATER             => '',
                     92:       $resObj->TRIES_LEFT             => '',
                     93:       $resObj->INCORRECT              => '',
                     94:       $resObj->OPEN                   => '',
                     95:       $resObj->NOTHING_SET            => '' );
1.136     bowersj2   96: # And a special case in the nav map; what to do when the assignment
                     97: # is not yet done and due in less then 24 hours
                     98: my $hurryUpColor = "#FF0000";
1.130     www        99: 
1.1       www       100: sub handler {
1.99      bowersj2  101:     my $r = shift;
1.118     bowersj2  102:     real_handler($r);
                    103: }
                    104: 
                    105: sub real_handler {
                    106:     my $r = shift;
1.2       www       107: 
1.51      bowersj2  108:     # Handle header-only request
                    109:     if ($r->header_only) {
                    110:         if ($ENV{'browser.mathml'}) {
                    111:             $r->content_type('text/xml');
                    112:         } else {
                    113:             $r->content_type('text/html');
                    114:         }
                    115:         $r->send_http_header;
                    116:         return OK;
                    117:     }
                    118: 
                    119:     # Send header, don't cache this page
                    120:     if ($ENV{'browser.mathml'}) {
                    121:         $r->content_type('text/xml');
                    122:     } else {
                    123:         $r->content_type('text/html');
                    124:     }
                    125:     &Apache::loncommon::no_cache($r);
                    126:     $r->send_http_header;
                    127: 
1.106     bowersj2  128:     # Create the nav map
1.168     bowersj2  129:     my $navmap = Apache::lonnavmaps::navmap->new(
1.51      bowersj2  130:                         $ENV{"request.course.fn"}.".db",
1.80      bowersj2  131:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
1.51      bowersj2  132: 
1.55      bowersj2  133: 
                    134:     if (!defined($navmap)) {
                    135:         my $requrl = $r->uri;
                    136:         $ENV{'user.error.msg'} = "$requrl:bre:0:0:Course not initialized";
                    137:         return HTTP_NOT_ACCEPTABLE;
                    138:     }
1.64      bowersj2  139: 
1.111     bowersj2  140:     $r->print("<html><head>\n");
1.150     www       141:     $r->print("<title>Navigate Course Contents</title>");
                    142: # ------------------------------------------------------------ Get query string
                    143:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['register']);
1.158     bowersj2  144:     
1.150     www       145: # ----------------------------------------------------- Force menu registration
                    146:     my $addentries='';
                    147:     if ($ENV{'form.register'}) {
                    148:        $addentries=' onLoad="'.&Apache::lonmenu::loadevents().
                    149: 	   '" onUnload="'.&Apache::lonmenu::unloadevents().'"';
                    150:        $r->print(&Apache::lonmenu::registerurl(1));
                    151:     }
1.111     bowersj2  152: 
1.64      bowersj2  153:     # Header
1.150     www       154:     $r->print('</head>'.
                    155:               &Apache::loncommon::bodytag('Navigate Course Contents','',
1.151     www       156:                                     $addentries,'','',$ENV{'form.register'}));
1.64      bowersj2  157:     $r->print('<script>window.focus();</script>');
1.101     bowersj2  158: 
1.124     bowersj2  159:     $r->rflush();
                    160: 
                    161:     # Now that we've displayed some stuff to the user, init the navmap
                    162:     $navmap->init();
                    163: 
1.205   ! bowersj2  164:     $r->print('<br>');
1.95      bowersj2  165:     $r->rflush();
                    166: 
1.55      bowersj2  167:     # Check that it's defined
                    168:     if (!($navmap->courseMapDefined())) {
                    169:         $r->print('<font size="+2" color="red">Coursemap undefined.</font>' .
                    170:                   '</body></html>');
                    171:         return OK;
                    172:     }
                    173: 
1.178     bowersj2  174:     # See if there's only one map in the top-level, if we don't
                    175:     # already have a filter... if so, automatically display it
1.179     bowersj2  176:     if ($ENV{QUERY_STRING} !~ /filter/) {
1.178     bowersj2  177:         my $iterator = $navmap->getIterator(undef, undef, undef, 0);
                    178:         my $depth = 1;
                    179:         $iterator->next();
                    180:         my $curRes = $iterator->next();
                    181:         my $sequenceCount = 0;
                    182:         my $sequenceId;
                    183:         while ($depth > 0) {
                    184:             if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
                    185:             if ($curRes == $iterator->END_MAP()) { $depth--; }
                    186:             
                    187:             if (ref($curRes) && $curRes->is_sequence()) {
                    188:                 $sequenceCount++;
                    189:                 $sequenceId = $curRes->map_pc();
1.179     bowersj2  190:             }
1.178     bowersj2  191:             
                    192:             $curRes = $iterator->next();
                    193:         }
                    194:         
                    195:         if ($sequenceCount == 1) {
                    196:             # The automatic iterator creation in the render call 
                    197:             # will pick this up. We know the condition because
                    198:             # the defined($ENV{'form.filter'}) also ensures this
                    199:             # is a fresh call.
                    200:             $ENV{'form.filter'} = "$sequenceId";
1.155     bowersj2  201:         }
                    202:     }
                    203: 
1.191     bowersj2  204:     my $jumpToFirstHomework = 0;
1.184     bowersj2  205:     # Check to see if the student is jumping to next open, do-able problem
                    206:     if ($ENV{QUERY_STRING} eq 'jumpToFirstHomework') {
1.191     bowersj2  207:         $jumpToFirstHomework = 1;
1.184     bowersj2  208:         # Find the next homework problem that they can do.
                    209:         my $iterator = $navmap->getIterator(undef, undef, undef, 1);
                    210:         my $depth = 1;
                    211:         $iterator->next();
                    212:         my $curRes = $iterator->next();
                    213:         my $foundDoableProblem = 0;
                    214:         my $problemRes;
                    215:         
                    216:         while ($depth > 0 && !$foundDoableProblem) {
                    217:             if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
                    218:             if ($curRes == $iterator->END_MAP()) { $depth--; }
                    219: 
                    220:             if (ref($curRes) && $curRes->is_problem()) {
                    221:                 my $status = $curRes->status();
1.191     bowersj2  222:                 if ($curRes->completable()) {
1.184     bowersj2  223:                     $problemRes = $curRes;
                    224:                     $foundDoableProblem = 1;
                    225: 
                    226:                     # Pop open all previous maps
                    227:                     my $stack = $iterator->getStack();
                    228:                     pop @$stack; # last resource in the stack is the problem
                    229:                                  # itself, which we don't need in the map stack
                    230:                     my @mapPcs = map {$_->map_pc()} @$stack;
                    231:                     $ENV{'form.filter'} = join(',', @mapPcs);
                    232: 
                    233:                     # Mark as both "here" and "jump"
                    234:                     $ENV{'form.postsymb'} = $curRes->symb();
                    235:                 }
                    236:             }
                    237:         } continue {
                    238:             $curRes = $iterator->next();
                    239:         }
                    240: 
                    241:         # If we found no problems, print a note to that effect.
                    242:         if (!$foundDoableProblem) {
                    243:             $r->print("<font size='+2'>All homework assignments have been completed.</font><br /><br />");
                    244:         }
                    245:     } else {
                    246:         $r->print("<a href='navmaps?jumpToFirstHomework'>" .
                    247:                   "Go To My First Homework Problem</a><br />");
                    248:     }
                    249: 
1.191     bowersj2  250:     my $suppressEmptySequences = 0;
                    251:     my $filterFunc = undef;
1.201     bowersj2  252:     my $resource_no_folder_link = 0;
                    253: 
1.191     bowersj2  254:     # Display only due homework.
                    255:     my $showOnlyHomework = 0;
                    256:     if ($ENV{QUERY_STRING} eq 'showOnlyHomework') {
                    257:         $showOnlyHomework = 1;
                    258:         $suppressEmptySequences = 1;
                    259:         $filterFunc = sub { my $res = shift; 
1.201     bowersj2  260:                             return $res->completable() || $res->is_map();
1.191     bowersj2  261:                         };
                    262:         $r->print("<p><font size='+2'>Uncompleted Homework</font></p>");
                    263:         $ENV{'form.filter'} = '';
                    264:         $ENV{'form.condition'} = 1;
1.201     bowersj2  265: 	$resource_no_folder_link = 1;
1.191     bowersj2  266:     } else {
                    267:         $r->print("<a href='navmaps?showOnlyHomework'>" .
                    268:                   "Show Only Uncompleted Homework</a><br />");
                    269:     }
                    270: 
1.133     bowersj2  271:     # renderer call
1.191     bowersj2  272:     my $renderArgs = { 'cols' => [0,1,2,3],
                    273:                        'url' => '/adm/navmaps',
                    274:                        'navmap' => $navmap,
                    275:                        'suppressNavmap' => 1,
                    276:                        'suppressEmptySequences' => $suppressEmptySequences,
                    277:                        'filterFunc' => $filterFunc,
1.201     bowersj2  278: 		       'resource_no_folder_link' => $resource_no_folder_link,
1.191     bowersj2  279:                        'r' => $r};
                    280:     my $render = render($renderArgs);
                    281:     $navmap->untieHashes();
1.133     bowersj2  282: 
1.191     bowersj2  283:     # If no resources were printed, print a reassuring message so the
                    284:     # user knows there was no error.
                    285:     if ($renderArgs->{'counter'} == 0) {
                    286:         if ($showOnlyHomework) {
                    287:             $r->print("<p><font size='+1'>All homework is currently completed.</font></p>");
                    288:         } else { # both jumpToFirstHomework and normal use the same: course must be empty
                    289:             $r->print("<p><font size='+1'>This course is empty.</font></p>");
                    290:         }
                    291:     }
1.51      bowersj2  292: 
1.128     bowersj2  293:     $r->print("</body></html>");
1.134     bowersj2  294:     $r->rflush();
1.59      bowersj2  295: 
1.51      bowersj2  296:     return OK;
                    297: }
                    298: 
                    299: # Convenience functions: Returns a string that adds or subtracts
                    300: # the second argument from the first hash, appropriate for the 
                    301: # query string that determines which folders to recurse on
                    302: sub addToFilter {
                    303:     my $hashIn = shift;
                    304:     my $addition = shift;
                    305:     my %hash = %$hashIn;
                    306:     $hash{$addition} = 1;
                    307: 
                    308:     return join (",", keys(%hash));
                    309: }
                    310: 
                    311: sub removeFromFilter {
                    312:     my $hashIn = shift;
                    313:     my $subtraction = shift;
                    314:     my %hash = %$hashIn;
                    315: 
                    316:     delete $hash{$subtraction};
                    317:     return join(",", keys(%hash));
                    318: }
                    319: 
                    320: # Convenience function: Given a stack returned from getStack on the iterator,
                    321: # return the correct src() value.
                    322: # Later, this should add an anchor when we start putting anchors in pages.
                    323: sub getLinkForResource {
                    324:     my $stack = shift;
                    325:     my $res;
                    326: 
                    327:     # Check to see if there are any pages in the stack
                    328:     foreach $res (@$stack) {
                    329:         if (defined($res) && $res->is_page()) {
                    330:             return $res->src();
                    331:         }
                    332:     }
                    333: 
                    334:     # Failing that, return the src of the last resource that is defined
                    335:     # (when we first recurse on a map, it puts an undefined resource
                    336:     # on the bottom because $self->{HERE} isn't defined yet, and we
                    337:     # want the src for the map anyhow)
                    338:     foreach (@$stack) {
                    339:         if (defined($_)) { $res = $_; }
                    340:     }
                    341: 
                    342:     return $res->src();
                    343: }
                    344: 
1.53      bowersj2  345: # Convenience function: This seperates the logic of how to create
                    346: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
                    347: # etc.) into a seperate function. It takes a resource object as the
                    348: # first parameter, and the part number of the resource as the second.
                    349: # It's basically a big switch statement on the status of the resource.
                    350: 
                    351: sub getDescription {
                    352:     my $res = shift;
                    353:     my $part = shift;
1.69      bowersj2  354:     my $status = $res->status($part);
1.53      bowersj2  355: 
1.182     bowersj2  356:     if ($status == $res->NETWORK_FAILURE) { 
                    357:         return "Having technical difficulties; please check status later"; 
                    358:     }
1.53      bowersj2  359:     if ($status == $res->NOTHING_SET) {
                    360:         return "Not currently assigned.";
                    361:     }
                    362:     if ($status == $res->OPEN_LATER) {
1.73      bowersj2  363:         return "Open " . timeToHumanString($res->opendate($part));
1.53      bowersj2  364:     }
                    365:     if ($status == $res->OPEN) {
1.79      bowersj2  366:         if ($res->duedate($part)) {
1.73      bowersj2  367:             return "Due " . timeToHumanString($res->duedate($part));
1.66      bowersj2  368:         } else {
                    369:             return "Open, no due date";
                    370:         }
1.53      bowersj2  371:     }
1.54      bowersj2  372:     if ($status == $res->PAST_DUE_ANSWER_LATER) {
1.73      bowersj2  373:         return "Answer open " . timeToHumanString($res->answerdate($part));
1.54      bowersj2  374:     }
                    375:     if ($status == $res->PAST_DUE_NO_ANSWER) {
1.73      bowersj2  376:         return "Was due " . timeToHumanString($res->duedate($part));
1.53      bowersj2  377:     }
                    378:     if ($status == $res->ANSWER_OPEN) {
                    379:         return "Answer available";
                    380:     }
1.59      bowersj2  381:     if ($status == $res->EXCUSED) {
1.66      bowersj2  382:         return "Excused by instructor";
1.59      bowersj2  383:     }
1.69      bowersj2  384:     if ($status == $res->ATTEMPTED) {
1.200     bowersj2  385:         return "Answer submitted, not yet graded.";
1.69      bowersj2  386:     }
1.59      bowersj2  387:     if ($status == $res->TRIES_LEFT) {
1.79      bowersj2  388:         my $tries = $res->tries($part);
                    389:         my $maxtries = $res->maxtries($part);
                    390:         my $triesString = "";
                    391:         if ($tries && $maxtries) {
                    392:             $triesString = "<font size=\"-1\"><i>($tries of $maxtries tries used)</i></font>";
                    393:             if ($maxtries > 1 && $maxtries - $tries == 1) {
                    394:                 $triesString = "<b>$triesString</b>";
                    395:             }
                    396:         }
1.66      bowersj2  397:         if ($res->duedate()) {
1.73      bowersj2  398:             return "Due " . timeToHumanString($res->duedate($part)) .
1.66      bowersj2  399:                 " $triesString";
                    400:         } else {
                    401:             return "No due date $triesString";
                    402:         }
1.59      bowersj2  403:     }
1.185     bowersj2  404:     if ($status == $res->ANSWER_SUBMITTED) {
                    405:         return 'Answer submitted';
                    406:     }
1.53      bowersj2  407: }
                    408: 
1.115     bowersj2  409: # Convenience function, so others can use it: Is the problem due in less then
                    410: # 24 hours, and still can be done?
                    411: 
                    412: sub dueInLessThen24Hours {
                    413:     my $res = shift;
                    414:     my $part = shift;
                    415:     my $status = $res->status($part);
                    416: 
                    417:     return ($status == $res->OPEN() || $status == $res->ATTEMPTED() ||
                    418:             $status == $res->TRIES_LEFT()) &&
                    419:            $res->duedate() && $res->duedate() < time()+(24*60*60) &&
                    420:            $res->duedate() > time();
                    421: }
                    422: 
                    423: # Convenience function, so others can use it: Is there only one try remaining for the
                    424: # part, with more then one try to begin with, not due yet and still can be done?
                    425: sub lastTry {
                    426:     my $res = shift;
                    427:     my $part = shift;
                    428: 
                    429:     my $tries = $res->tries($part);
                    430:     my $maxtries = $res->maxtries($part);
                    431:     return $tries && $maxtries && $maxtries > 1 &&
                    432:         $maxtries - $tries == 1 && $res->duedate() &&
                    433:         $res->duedate() > time();
                    434: }
                    435: 
1.101     bowersj2  436: # This puts a human-readable name on the ENV variable.
1.177     www       437: 
1.68      bowersj2  438: sub advancedUser {
1.177     www       439:     return $ENV{'request.role.adv'};
1.68      bowersj2  440: }
                    441: 
1.73      bowersj2  442: 
                    443: # timeToHumanString takes a time number and converts it to a
                    444: # human-readable representation, meant to be used in the following
                    445: # manner:
                    446: # print "Due $timestring"
                    447: # print "Open $timestring"
                    448: # print "Answer available $timestring"
                    449: # Very, very, very, VERY English-only... goodness help a localizer on
                    450: # this func...
1.53      bowersj2  451: sub timeToHumanString {
1.58      albertel  452:     my ($time) = @_;
                    453:     # zero, '0' and blank are bad times
1.73      bowersj2  454:     if (!$time) {
                    455:         return 'never';
                    456:     }
                    457: 
                    458:     my $now = time();
                    459: 
                    460:     my @time = localtime($time);
                    461:     my @now = localtime($now);
                    462: 
                    463:     # Positive = future
                    464:     my $delta = $time - $now;
                    465: 
                    466:     my $minute = 60;
                    467:     my $hour = 60 * $minute;
                    468:     my $day = 24 * $hour;
                    469:     my $week = 7 * $day;
                    470:     my $inPast = 0;
                    471: 
                    472:     # Logic in comments:
                    473:     # Is it now? (extremely unlikely)
                    474:     if ( $delta == 0 ) {
                    475:         return "this instant";
                    476:     }
                    477: 
                    478:     if ($delta < 0) {
                    479:         $inPast = 1;
                    480:         $delta = -$delta;
                    481:     }
                    482: 
                    483:     if ( $delta > 0 ) {
1.101     bowersj2  484: 
1.73      bowersj2  485:         my $tense = $inPast ? " ago" : "";
                    486:         my $prefix = $inPast ? "" : "in ";
1.101     bowersj2  487:         
                    488:         # Less then a minute
1.73      bowersj2  489:         if ( $delta < $minute ) {
                    490:             if ($delta == 1) { return "${prefix}1 second$tense"; }
                    491:             return "$prefix$delta seconds$tense";
                    492:         }
                    493: 
1.101     bowersj2  494:         # Less then an hour
1.73      bowersj2  495:         if ( $delta < $hour ) {
                    496:             # If so, use minutes
                    497:             my $minutes = floor($delta / 60);
                    498:             if ($minutes == 1) { return "${prefix}1 minute$tense"; }
                    499:             return "$prefix$minutes minutes$tense";
                    500:         }
                    501:         
                    502:         # Is it less then 24 hours away? If so,
                    503:         # display hours + minutes
                    504:         if ( $delta < $hour * 24) {
                    505:             my $hours = floor($delta / $hour);
                    506:             my $minutes = floor(($delta % $hour) / $minute);
                    507:             my $hourString = "$hours hours";
                    508:             my $minuteString = ", $minutes minutes";
                    509:             if ($hours == 1) {
                    510:                 $hourString = "1 hour";
                    511:             }
                    512:             if ($minutes == 1) {
                    513:                 $minuteString = ", 1 minute";
                    514:             }
                    515:             if ($minutes == 0) {
                    516:                 $minuteString = "";
                    517:             }
                    518:             return "$prefix$hourString$minuteString$tense";
                    519:         }
                    520: 
                    521:         # Less then 5 days away, display day of the week and
                    522:         # HH:MM
                    523:         if ( $delta < $day * 5 ) {
1.85      bowersj2  524:             my $timeStr = strftime("%A, %b %e at %I:%M %P", localtime($time));
1.73      bowersj2  525:             $timeStr =~ s/12:00 am/midnight/;
                    526:             $timeStr =~ s/12:00 pm/noon/;
                    527:             return ($inPast ? "last " : "next ") .
                    528:                 $timeStr;
                    529:         }
                    530:         
                    531:         # Is it this year?
                    532:         if ( $time[5] == $now[5]) {
                    533:             # Return on Month Day, HH:MM meridian
                    534:             my $timeStr = strftime("on %A, %b %e at %I:%M %P", localtime($time));
                    535:             $timeStr =~ s/12:00 am/midnight/;
                    536:             $timeStr =~ s/12:00 pm/noon/;
                    537:             return $timeStr;
                    538:         }
                    539: 
                    540:         # Not this year, so show the year
                    541:         my $timeStr = strftime("on %A, %b %e %G at %I:%M %P", localtime($time));
                    542:         $timeStr =~ s/12:00 am/midnight/;
                    543:         $timeStr =~ s/12:00 pm/noon/;
                    544:         return $timeStr;
1.58      albertel  545:     }
1.53      bowersj2  546: }
                    547: 
1.51      bowersj2  548: 
1.133     bowersj2  549: =pod
                    550: 
1.174     albertel  551: =head1 NAME
                    552: 
                    553: Apache::lonnavmap - Subroutines to handle and render the navigation maps
                    554: 
                    555: =head1 SYNOPSIS
                    556: 
                    557: The main handler generates the navigational listing for the course,
                    558: the other objects export this information in a usable fashion for
1.205   ! bowersj2  559: other modules.
1.133     bowersj2  560: 
1.205   ! bowersj2  561: =head1 Subroutine: render
1.133     bowersj2  562: 
1.174     albertel  563: The navmap renderer package provides a sophisticated rendering of the
                    564: standard navigation maps interface into HTML. The provided nav map
                    565: handler is actually just a glorified call to this.
1.133     bowersj2  566: 
1.174     albertel  567: Because of the large number of parameters this function presents,
                    568: instead of passing it arguments as is normal, pass it in an anonymous
                    569: hash with the given options. This is because there is no obvious order
                    570: you may wish to override these in and a hash is easier to read and
                    571: understand then "undef, undef, undef, 1, undef, undef, renderButton,
                    572: undef, 0" when you mostly want default behaviors.
                    573: 
                    574: The package provides a function called 'render', called as
1.205   ! bowersj2  575: Apache::lonnavmaps::render({}).
1.51      bowersj2  576: 
1.133     bowersj2  577: =head2 Overview of Columns
1.51      bowersj2  578: 
1.174     albertel  579: The renderer will build an HTML table for the navmap and return
                    580: it. The table is consists of several columns, and a row for each
                    581: resource (or possibly each part). You tell the renderer how many
                    582: columns to create and what to place in each column, optionally using
1.205   ! bowersj2  583: one or more of the prepared columns, and the renderer will assemble
1.174     albertel  584: the table.
                    585: 
                    586: Any additional generally useful column types should be placed in the
                    587: renderer code here, so anybody can use it anywhere else. Any code
                    588: specific to the current application (such as the addition of <input>
                    589: elements in a column) should be placed in the code of the thing using
                    590: the renderer.
                    591: 
                    592: At the core of the renderer is the array reference COLS (see Example
                    593: section below for how to pass this correctly). The COLS array will
                    594: consist of entries of one of two types of things: Either an integer
                    595: representing one of the pre-packaged column types, or a sub reference
                    596: that takes a resource reference, a part number, and a reference to the
                    597: argument hash passed to the renderer, and returns a string that will
                    598: be inserted into the HTML representation as it.
                    599: 
                    600: The pre-packaged column names are refered to by constants in the
1.205   ! bowersj2  601: Apache::lonnavmaps namespace. The following currently exist:
1.51      bowersj2  602: 
1.174     albertel  603: =over 4
1.51      bowersj2  604: 
1.174     albertel  605: =item * B<resource>:
1.51      bowersj2  606: 
1.174     albertel  607: The general info about the resource: Link, icon for the type, etc. The
                    608: first column in the standard nav map display. This column also accepts
1.205   ! bowersj2  609: the following parameters in the renderer hash:
1.51      bowersj2  610: 
1.133     bowersj2  611: =over 4
1.51      bowersj2  612: 
1.174     albertel  613: =item * B<resource_nolink>:
1.51      bowersj2  614: 
1.174     albertel  615: If true, the resource will not be linked. Default: false, resource
                    616: will have links.
                    617: 
                    618: =item * B<resource_part_count>:
1.51      bowersj2  619: 
1.174     albertel  620: If true (default), the resource will show a part count if the full
                    621: part list is not displayed. If false, the resource will never show a
                    622: part count.
1.133     bowersj2  623: 
1.174     albertel  624: =item * B<resource_no_folder_link>:
1.133     bowersj2  625: 
1.174     albertel  626: If true, the resource's folder will not be clickable to open or close
                    627: it. Default is false. True implies printCloseAll is false, since you
                    628: can't close or open folders when this is on anyhow.
1.144     bowersj2  629: 
1.133     bowersj2  630: =back
1.51      bowersj2  631: 
1.174     albertel  632: =item B<communication_status>:
                    633: 
                    634: Whether there is discussion on the resource, email for the user, or
                    635: (lumped in here) perl errors in the execution of the problem. This is
                    636: the second column in the main nav map.
                    637: 
                    638: =item B<quick_status>:
1.51      bowersj2  639: 
1.174     albertel  640: An icon for the status of a problem, with four possible states:
                    641: Correct, incorrect, open, or none (not open yet, not a problem). The
                    642: third column of the standard navmap.
1.51      bowersj2  643: 
1.174     albertel  644: =item B<long_status>:
                    645: 
                    646: A text readout of the details of the current status of the problem,
                    647: such as "Due in 22 hours". The fourth column of the standard navmap.
1.51      bowersj2  648: 
1.133     bowersj2  649: =back
1.51      bowersj2  650: 
1.133     bowersj2  651: If you add any others please be sure to document them here.
1.51      bowersj2  652: 
1.174     albertel  653: An example of a column renderer that will show the ID number of a
                    654: resource, along with the part name if any:
1.51      bowersj2  655: 
1.133     bowersj2  656:  sub { 
                    657:   my ($resource, $part, $params) = @_;   
                    658:   if ($part) { return '<td>' . $resource->{ID} . ' ' . $part . '</td>'; }
                    659:   return '<td>' . $resource->{ID} . '</td>';
                    660:  }
1.51      bowersj2  661: 
1.174     albertel  662: Note these functions are responsible for the TD tags, which allow them
                    663: to override vertical and horizontal alignment, etc.
1.130     www       664: 
1.133     bowersj2  665: =head2 Parameters
1.115     bowersj2  666: 
1.174     albertel  667: Most of these parameters are only useful if you are *not* using the
                    668: folder interface (i.e., the default first column), which is probably
                    669: the common case. If you are using this interface, then you should be
                    670: able to get away with just using 'cols' (to specify the columns
                    671: shown), 'url' (necessary for the folders to link to the current screen
                    672: correctly), and possibly 'queryString' if your app calls for it. In
                    673: that case, maintaining the state of the folders will be done
                    674: automatically.
1.140     bowersj2  675: 
1.133     bowersj2  676: =over 4
1.51      bowersj2  677: 
1.174     albertel  678: =item * B<iterator>:
                    679: 
                    680: A reference to a fresh ::iterator to use from the navmaps. The
                    681: rendering will reflect the options passed to the iterator, so you can
                    682: use that to just render a certain part of the course, if you like. If
                    683: one is not passed, the renderer will attempt to construct one from
                    684: ENV{'form.filter'} and ENV{'form.condition'} information, plus the
                    685: 'iterator_map' parameter if any.
                    686: 
                    687: =item * B<iterator_map>:
                    688: 
                    689: If you are letting the renderer do the iterator handling, you can
                    690: instruct the renderer to render only a particular map by passing it
                    691: the source of the map you want to process, like
                    692: '/res/103/jerf/navmap.course.sequence'.
                    693: 
                    694: =item * B<navmap>:
                    695: 
                    696: A reference to a navmap, used only if an iterator is not passed in. If
                    697: this is necessary to make an iterator but it is not passed in, a new
                    698: one will be constructed based on ENV info. This is useful to do basic
                    699: error checking before passing it off to render.
                    700: 
                    701: =item * B<r>:
                    702: 
                    703: The standard Apache response object. This must be passed to the
                    704: renderer or the course hash will be locked.
                    705: 
                    706: =item * B<cols>:
                    707: 
                    708: An array reference
                    709: 
                    710: =item * B<showParts>:
                    711: 
                    712: A flag. If yes (default), a line for the resource itself, and a line
                    713: for each part will be displayed. If not, only one line for each
                    714: resource will be displayed.
                    715: 
                    716: =item * B<condenseParts>:
                    717: 
                    718: A flag. If yes (default), if all parts of the problem have the same
                    719: status and that status is Nothing Set, Correct, or Network Failure,
                    720: then only one line will be displayed for that resource anyhow. If no,
                    721: all parts will always be displayed. If showParts is 0, this is
                    722: ignored.
                    723: 
                    724: =item * B<jumpCount>:
                    725: 
                    726: A string identifying the URL to place the anchor 'curloc' at. Default
                    727: to no anchor at all. It is the responsibility of the renderer user to
                    728: ensure that the #curloc is in the URL. By default, determined through
                    729: the use of the ENV{} 'jump' information, and should normally "just
                    730: work" correctly.
1.144     bowersj2  731: 
1.174     albertel  732: =item * B<here>:
1.140     bowersj2  733: 
1.174     albertel  734: A Symb identifying where to place the 'here' marker. Default empty,
                    735: which means no marker.
1.92      bowersj2  736: 
1.174     albertel  737: =item * B<indentString>:
1.164     bowersj2  738: 
1.174     albertel  739: A string identifying the indentation string to use. By default, this
                    740: is a 25 pixel whitespace image with no alt text.
1.92      bowersj2  741: 
1.174     albertel  742: =item * B<queryString>:
1.51      bowersj2  743: 
1.174     albertel  744: A string which will be prepended to the query string used when the
                    745: folders are opened or closed.
1.55      bowersj2  746: 
1.174     albertel  747: =item * B<url>:
1.84      bowersj2  748: 
1.174     albertel  749: The url the folders will link to, which should be the current
                    750: page. Required if the resource info column is shown.
1.115     bowersj2  751: 
1.174     albertel  752: =item * B<currentJumpIndex>:
1.55      bowersj2  753: 
1.174     albertel  754: Describes the currently-open row number to cause the browser to jump
                    755: to, because the user just opened that folder. By default, pulled from
                    756: the Jump information in the ENV{'form.*'}.
1.51      bowersj2  757: 
1.174     albertel  758: =item * B<printKey>:
1.51      bowersj2  759: 
1.174     albertel  760: If true, print the key that appears on the top of the standard
                    761: navmaps. Default is false.
1.139     bowersj2  762: 
1.174     albertel  763: =item * B<printCloseAll>:
1.140     bowersj2  764: 
1.174     albertel  765: If true, print the "Close all folders" or "open all folders"
                    766: links. Default is true.
1.140     bowersj2  767: 
1.174     albertel  768: =item * B<filterFunc>:
1.153     bowersj2  769: 
1.174     albertel  770: A function that takes the resource object as its only parameter and
                    771: returns a true or false value. If true, the resource is displayed. If
                    772: false, it is simply skipped in the display. By default, all resources
                    773: are shown.
                    774: 
1.190     bowersj2  775: =item * B<suppressEmptySequences>:
                    776: 
                    777: If you're using a filter function, and displaying sequences to orient
                    778: the user, then frequently some sequences will be empty. Setting this to
                    779: true will cause those sequences not to display, so as not to confuse the
                    780: user into thinking that if the sequence is there there should be things
                    781: under it.
                    782: 
1.174     albertel  783: =item * B<suppressNavmaps>:
                    784: 
                    785: If true, will not display Navigate Content resources. Default to
                    786: false.
1.143     bowersj2  787: 
1.133     bowersj2  788: =back
1.51      bowersj2  789: 
1.133     bowersj2  790: =head2 Additional Info
1.51      bowersj2  791: 
1.174     albertel  792: In addition to the parameters you can pass to the renderer, which will
                    793: be passed through unchange to the column renderers, the renderer will
                    794: generate the following information which your renderer may find
                    795: useful:
                    796: 
                    797: If you want to know how many rows were printed, the 'counter' element
                    798: of the hash passed into the render function will contain the
                    799: count. You may want to check whether any resources were printed at
                    800: all.
1.145     bowersj2  801: 
1.133     bowersj2  802: =over 4
1.59      bowersj2  803: 
1.133     bowersj2  804: =back
1.59      bowersj2  805: 
1.133     bowersj2  806: =cut
1.59      bowersj2  807: 
1.133     bowersj2  808: sub resource { return 0; }
                    809: sub communication_status { return 1; }
                    810: sub quick_status { return 2; }
                    811: sub long_status { return 3; }
1.124     bowersj2  812: 
1.133     bowersj2  813: # Data for render_resource
1.51      bowersj2  814: 
1.133     bowersj2  815: sub render_resource {
                    816:     my ($resource, $part, $params) = @_;
1.51      bowersj2  817: 
1.133     bowersj2  818:     my $nonLinkedText = ''; # stuff after resource title not in link
1.51      bowersj2  819: 
1.134     bowersj2  820:     my $link = $params->{"resourceLink"};
                    821:     my $src = $resource->src();
                    822:     my $it = $params->{"iterator"};
1.133     bowersj2  823:     my $filter = $it->{FILTER};
                    824: 
                    825:     my $title = $resource->compTitle();
                    826:     if ($src =~ /^\/uploaded\//) {
                    827:         $nonLinkedText=$title;
                    828:         $title = '';
                    829:     }
                    830:     my $partLabel = "";
                    831:     my $newBranchText = "";
                    832:     
                    833:     # If this is a new branch, label it so
                    834:     if ($params->{'isNewBranch'}) {
                    835:         $newBranchText = "<img src='/adm/lonIcons/branch.gif' border='0' />";
1.51      bowersj2  836:     }
                    837: 
1.133     bowersj2  838:     # links to open and close the folder
                    839:     my $linkopen = "<a href='$link'>";
                    840:     my $linkclose = "</a>";
1.51      bowersj2  841: 
1.204     albertel  842:     # Default icon: unknown page
                    843:     my $icon = "<img src='/adm/lonIcons/unknown.gif' alt='' border='0' />";
1.133     bowersj2  844:     
                    845:     if ($resource->is_problem()) {
1.192     bowersj2  846:         if ($part eq '0' || $params->{'condensed'}) {
1.133     bowersj2  847:             $icon = '<img src="/adm/lonIcons/problem.gif" alt="" border="0" />';
                    848:         } else {
                    849:             $icon = $params->{'indentString'};
                    850:         }
1.204     albertel  851:     } else {
                    852: 	my $curfext= (split (/\./,$resource->src))[-1];
                    853: 	my $embstyle = &Apache::loncommon::fileembstyle($curfext);
                    854: 	# The unless conditional that follows is a bit of overkill
                    855: 	if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                    856: 	    $icon = "<img src='/adm/lonIcons/$curfext.gif' alt='' border='0' />";
                    857: 	}
1.133     bowersj2  858:     }
1.51      bowersj2  859: 
1.133     bowersj2  860:     # Display the correct map icon to open or shut map
                    861:     if ($resource->is_map()) {
                    862:         my $mapId = $resource->map_pc();
                    863:         my $nowOpen = !defined($filter->{$mapId});
                    864:         if ($it->{CONDITION}) {
                    865:             $nowOpen = !$nowOpen;
                    866:         }
1.144     bowersj2  867: 
1.205   ! bowersj2  868: 	my $folderType = $resource->is_sequence() ? 'folder' : 'page';
        !           869: 
1.144     bowersj2  870:         if (!$params->{'resource_no_folder_link'}) {
1.205   ! bowersj2  871:             $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') . '.gif';
1.144     bowersj2  872:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
                    873: 
                    874:             $linkopen = "<a href='" . $params->{'url'} . '?' . 
                    875:                 $params->{'queryString'} . '&filter=';
                    876:             $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
                    877:                 addToFilter($filter, $mapId) :
                    878:                 removeFromFilter($filter, $mapId);
                    879:             $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
                    880:                 . $params->{'hereType'} . '&here=' .
                    881:                 &Apache::lonnet::escape($params->{'here'}) . 
1.159     bowersj2  882:                 '&jump=' .
1.144     bowersj2  883:                 &Apache::lonnet::escape($resource->symb()) . 
                    884:                 "&folderManip=1'>";
                    885:         } else {
                    886:             # Don't allow users to manipulate folder
1.205   ! bowersj2  887:             $icon = "navmap.$folderType." . ($nowOpen ? 'closed' : 'open') .
1.144     bowersj2  888:                 '.nomanip.gif';
                    889:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
                    890: 
                    891:             $linkopen = "";
                    892:             $linkclose = "";
                    893:         }
1.133     bowersj2  894:     }
1.51      bowersj2  895: 
1.133     bowersj2  896:     if ($resource->randomout()) {
                    897:         $nonLinkedText .= ' <i>(hidden)</i> ';
                    898:     }
                    899:     
                    900:     # We're done preparing and finally ready to start the rendering
                    901:     my $result = "<td align='left' valign='center'>";
1.140     bowersj2  902: 
                    903:     my $indentLevel = $params->{'indentLevel'};
                    904:     if ($newBranchText) { $indentLevel--; }
                    905: 
1.133     bowersj2  906:     # print indentation
1.140     bowersj2  907:     for (my $i = 0; $i < $indentLevel; $i++) {
1.133     bowersj2  908:         $result .= $params->{'indentString'};
1.84      bowersj2  909:     }
                    910: 
1.133     bowersj2  911:     # Decide what to display
                    912:     $result .= "$newBranchText$linkopen$icon$linkclose";
                    913:     
                    914:     my $curMarkerBegin = '';
                    915:     my $curMarkerEnd = '';
1.51      bowersj2  916: 
1.133     bowersj2  917:     # Is this the current resource?
1.158     bowersj2  918:     if (!$params->{'displayedHereMarker'} && 
                    919:         $resource->symb() eq $params->{'here'} ) {
1.133     bowersj2  920:         $curMarkerBegin = '<font color="red" size="+2">&gt; </font>';
                    921:         $curMarkerEnd = '<font color="red" size="+2">&lt;</font>';
1.158     bowersj2  922:         $params->{'displayedHereMarker'} = 1;
1.51      bowersj2  923:     }
                    924: 
1.192     bowersj2  925:     if ($resource->is_problem() && $part ne '0' && 
1.133     bowersj2  926:         !$params->{'condensed'}) {
                    927:         $partLabel = " (Part $part)";
                    928:         $title = "";
1.51      bowersj2  929:     }
                    930: 
1.163     bowersj2  931:     if ($params->{'condensed'} && $resource->countParts() > 1) {
1.133     bowersj2  932:         $nonLinkedText .= ' (' . $resource->countParts() . ' parts)';
1.51      bowersj2  933:     }
                    934: 
1.203     bowersj2  935:     if (!$params->{'resource_nolink'} && $src !~ /^\/uploaded\// &&
1.205   ! bowersj2  936: 	!$resource->is_sequence()) {
1.144     bowersj2  937:         $result .= "  $curMarkerBegin<a href='$link'>$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
                    938:     } else {
                    939:         $result .= "  $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
                    940:     }
1.51      bowersj2  941: 
1.133     bowersj2  942:     return $result;
                    943: }
1.51      bowersj2  944: 
1.133     bowersj2  945: sub render_communication_status {
                    946:     my ($resource, $part, $params) = @_;
1.134     bowersj2  947:     my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
                    948: 
                    949:     my $link = $params->{"resourceLink"};
                    950:     my $linkopen = "<a href='$link'>";
                    951:     my $linkclose = "</a>";
                    952: 
                    953:     if ($resource->hasDiscussion()) {
                    954:         $discussionHTML = $linkopen .
                    955:             '<img border="0" src="/adm/lonMisc/chat.gif" />' .
                    956:             $linkclose;
                    957:     }
                    958:     
                    959:     if ($resource->getFeedback()) {
                    960:         my $feedback = $resource->getFeedback();
                    961:         foreach (split(/\,/, $feedback)) {
                    962:             if ($_) {
                    963:                 $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
                    964:                     . &Apache::lonnet::escape($_) . '">'
                    965:                     . '<img src="/adm/lonMisc/feedback.gif" '
                    966:                     . 'border="0" /></a>';
                    967:             }
                    968:         }
                    969:     }
                    970:     
                    971:     if ($resource->getErrors()) {
                    972:         my $errors = $resource->getErrors();
                    973:         foreach (split(/,/, $errors)) {
                    974:             if ($_) {
                    975:                 $errorHTML .= '&nbsp;<a href="/adm/email?display='
                    976:                     . &Apache::lonnet::escape($_) . '">'
                    977:                     . '<img src="/adm/lonMisc/bomb.gif" '
                    978:                     . 'border="0" /></a>';
                    979:             }
                    980:         }
1.197     bowersj2  981:     }
                    982: 
                    983:     if ($params->{'multipart'} && $part != '0') {
                    984: 	$discussionHTML = $feedbackHTML = $errorHTML = '';
1.134     bowersj2  985:     }
                    986: 
                    987:     return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";
                    988: 
1.133     bowersj2  989: }
                    990: sub render_quick_status {
                    991:     my ($resource, $part, $params) = @_;
1.135     bowersj2  992:     my $result = "";
                    993:     my $firstDisplayed = !$params->{'condensed'} && 
                    994:         $params->{'multipart'} && $part eq "0";
                    995: 
                    996:     my $link = $params->{"resourceLink"};
                    997:     my $linkopen = "<a href='$link'>";
                    998:     my $linkclose = "</a>";
                    999: 
                   1000:     if ($resource->is_problem() &&
                   1001:         !$firstDisplayed) {
                   1002:         my $icon = $statusIconMap{$resource->status($part)};
                   1003:         my $alt = $iconAltTags{$icon};
                   1004:         if ($icon) {
                   1005:             $result .= "<td width='30' valign='center' width='50' align='right'>$linkopen<img width='25' height='25' src='/adm/lonIcons/$icon' border='0' alt='$alt' />$linkclose</td>\n";
                   1006:         } else {
                   1007:             $result .= "<td width='30'>&nbsp;</td>\n";
                   1008:         }
                   1009:     } else { # not problem, no icon
                   1010:         $result .= "<td width='30'>&nbsp;</td>\n";
                   1011:     }
                   1012: 
                   1013:     return $result;
1.133     bowersj2 1014: }
                   1015: sub render_long_status {
                   1016:     my ($resource, $part, $params) = @_;
1.136     bowersj2 1017:     my $result = "<td align='right' valign='center'>\n";
                   1018:     my $firstDisplayed = !$params->{'condensed'} && 
                   1019:         $params->{'multipart'} && $part eq "0";
                   1020:                 
                   1021:     my $color;
1.192     bowersj2 1022:     if ($resource->is_problem() && ($resource->countParts() <= 1 || $part ne '') ) {
1.136     bowersj2 1023:         $color = $colormap{$resource->status};
                   1024:         
                   1025:         if (dueInLessThen24Hours($resource, $part) ||
                   1026:             lastTry($resource, $part)) {
                   1027:             $color = $hurryUpColor;
                   1028:         }
                   1029:     }
                   1030:     
                   1031:     if ($resource->kind() eq "res" &&
                   1032:         $resource->is_problem() &&
                   1033:         !$firstDisplayed) {
                   1034:         if ($color) {$result .= "<font color=\"$color\"><b>"; }
                   1035:         $result .= getDescription($resource, $part);
                   1036:         if ($color) {$result .= "</b></font>"; }
                   1037:     }
                   1038:     if ($resource->is_map() && advancedUser() && $resource->randompick()) {
                   1039:         $result .= '(randomly select ' . $resource->randompick() .')';
                   1040:     }
                   1041:     
                   1042:     return $result;
1.51      bowersj2 1043: }
                   1044: 
1.133     bowersj2 1045: my @preparedColumns = (\&render_resource, \&render_communication_status,
                   1046:                        \&render_quick_status, \&render_long_status);
1.132     bowersj2 1047: 
                   1048: sub setDefault {
                   1049:     my ($val, $default) = @_;
                   1050:     if (!defined($val)) { return $default; }
                   1051:     return $val;
                   1052: }
                   1053: 
                   1054: sub render {
                   1055:     my $args = shift;
1.140     bowersj2 1056:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
                   1057:     my $result = '';
                   1058: 
1.132     bowersj2 1059:     # Configure the renderer.
                   1060:     my $cols = $args->{'cols'};
                   1061:     if (!defined($cols)) {
                   1062:         # no columns, no nav maps.
                   1063:         return '';
                   1064:     }
1.140     bowersj2 1065:     my $mustCloseNavMap = 0;
                   1066:     my $navmap;
                   1067:     if (defined($args->{'navmap'})) {
                   1068:         $navmap = $args->{'navmap'};
                   1069:     }
                   1070: 
1.158     bowersj2 1071:     my $r = $args->{'r'};
1.140     bowersj2 1072:     my $queryString = $args->{'queryString'};
1.159     bowersj2 1073:     my $jump = $args->{'jump'};
1.158     bowersj2 1074:     my $here = $args->{'here'};
1.153     bowersj2 1075:     my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
1.140     bowersj2 1076:     my $currentJumpDelta = 2; # change this to change how many resources are displayed
                   1077:                              # before the current resource when using #current
                   1078: 
                   1079:     # If we were passed 'here' information, we are not rendering
                   1080:     # after a folder manipulation, and we were not passed an
                   1081:     # iterator, make sure we open the folders to show the "here"
                   1082:     # marker
                   1083:     my $filterHash = {};
                   1084:     # Figure out what we're not displaying
                   1085:     foreach (split(/\,/, $ENV{"form.filter"})) {
                   1086:         if ($_) {
                   1087:             $filterHash->{$_} = "1";
                   1088:         }
                   1089:     }
                   1090: 
1.191     bowersj2 1091:     # Filter: Remember filter function and add our own filter: Refuse
                   1092:     # to show hidden resources unless the user can see them.
                   1093:     my $userCanSeeHidden = advancedUser();
                   1094:     my $filterFunc = setDefault($args->{'filterFunc'},
                   1095:                                 sub {return 1;});
                   1096:     if (!$userCanSeeHidden) {
                   1097:         # Without renaming the filterfunc, the server seems to go into
                   1098:         # an infinite loop
                   1099:         my $oldFilterFunc = $filterFunc;
                   1100:         $filterFunc = sub { my $res = shift; return !$res->randomout() && 
                   1101:                                 &$oldFilterFunc($res);};
                   1102:     }
                   1103: 
1.140     bowersj2 1104:     my $condition = 0;
                   1105:     if ($ENV{'form.condition'}) {
                   1106:         $condition = 1;
                   1107:     }
                   1108: 
                   1109:     if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
                   1110:         # Step 1: Check to see if we have a navmap
                   1111:         if (!defined($navmap)) {
1.171     bowersj2 1112:             $navmap = Apache::lonnavmaps::navmap->new(
1.140     bowersj2 1113:                         $ENV{"request.course.fn"}.".db",
                   1114:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
                   1115:             $mustCloseNavMap = 1;
                   1116:         }
                   1117:         $navmap->init();
                   1118: 
                   1119:         # Step two: Locate what kind of here marker is necessary
                   1120:         # Determine where the "here" marker is and where the screen jumps to.
                   1121: 
1.175     bowersj2 1122:         if ($ENV{'form.postsymb'}) {
                   1123:             $here = $jump = $ENV{'form.postsymb'};
1.140     bowersj2 1124:         } elsif ($ENV{'form.postdata'}) {
                   1125:             # couldn't find a symb, is there a URL?
                   1126:             my $currenturl = $ENV{'form.postdata'};
1.158     bowersj2 1127:             #$currenturl=~s/^http\:\/\///;
                   1128:             #$currenturl=~s/^[^\/]+//;
1.140     bowersj2 1129:             
1.158     bowersj2 1130:             $here = $jump = &Apache::lonnet::symbread($currenturl);
1.140     bowersj2 1131:         }
1.158     bowersj2 1132: 
1.140     bowersj2 1133:         # Step three: Ensure the folders are open
                   1134:         my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
                   1135:         my $depth = 1;
                   1136:         $mapIterator->next(); # discard the first BEGIN_MAP
                   1137:         my $curRes = $mapIterator->next();
                   1138:         my $found = 0;
                   1139:         
                   1140:         # We only need to do this if we need to open the maps to show the
                   1141:         # current position. This will change the counter so we can't count
                   1142:         # for the jump marker with this loop.
                   1143:         while ($depth > 0 && !$found) {
                   1144:             if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
                   1145:             if ($curRes == $mapIterator->END_MAP()) { $depth--; }
                   1146:             
1.158     bowersj2 1147:             if (ref($curRes) && $curRes->symb() eq $here) {
1.140     bowersj2 1148:                 my $mapStack = $mapIterator->getStack();
                   1149:                 
                   1150:                 # Ensure the parent maps are open
                   1151:                 for my $map (@{$mapStack}) {
                   1152:                     if ($condition) {
                   1153:                         undef $filterHash->{$map->map_pc()};
                   1154:                     } else {
                   1155:                         $filterHash->{$map->map_pc()} = 1;
                   1156:                     }
                   1157:                 }
                   1158:                 $found = 1;
                   1159:             }
                   1160:             
                   1161:             $curRes = $mapIterator->next();
                   1162:         }            
1.159     bowersj2 1163:     }        
1.140     bowersj2 1164: 
                   1165:     if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
                   1166:         # If this is a click on a folder or something, we want to preserve the "here"
                   1167:         # from the querystring, and get the new "jump" marker
                   1168:         $here = $ENV{'form.here'};
                   1169:         $jump = $ENV{'form.jump'};
                   1170:     } 
                   1171:     
1.132     bowersj2 1172:     my $it = $args->{'iterator'};
                   1173:     if (!defined($it)) {
1.140     bowersj2 1174:         # Construct a default iterator based on $ENV{'form.'} information
                   1175:         
                   1176:         # Step 1: Check to see if we have a navmap
                   1177:         if (!defined($navmap)) {
1.164     bowersj2 1178:             $navmap = Apache::lonnavmaps::navmap->new($r, 
1.140     bowersj2 1179:                         $ENV{"request.course.fn"}.".db",
                   1180:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
                   1181:             $mustCloseNavMap = 1;
                   1182:         }
                   1183:         # Paranoia: Make sure it's ready
                   1184:         $navmap->init();
                   1185: 
1.144     bowersj2 1186:         # See if we're being passed a specific map
                   1187:         if ($args->{'iterator_map'}) {
                   1188:             my $map = $args->{'iterator_map'};
1.145     bowersj2 1189:             $map = $navmap->getResourceByUrl($map);
1.144     bowersj2 1190:             my $firstResource = $map->map_start();
                   1191:             my $finishResource = $map->map_finish();
                   1192: 
                   1193:             $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
                   1194:         } else {
                   1195:             $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
                   1196:         }
1.132     bowersj2 1197:     }
                   1198:     
1.159     bowersj2 1199:     # (re-)Locate the jump point, if any
1.191     bowersj2 1200:     # Note this does not take filtering or hidden into account... need
                   1201:     # to be fixed?
1.159     bowersj2 1202:     my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
                   1203:     my $depth = 1;
                   1204:     $mapIterator->next();
                   1205:     my $curRes = $mapIterator->next();
                   1206:     my $foundJump = 0;
                   1207:     my $counter = 0;
                   1208:     
                   1209:     while ($depth > 0 && !$foundJump) {
                   1210:         if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
                   1211:         if ($curRes == $mapIterator->END_MAP()) { $depth--; }
                   1212:         if (ref($curRes)) { $counter++; }
                   1213:         
                   1214:         if (ref($curRes) && $jump eq $curRes->symb()) {
                   1215:             
                   1216:             # This is why we have to use the main iterator instead of the
                   1217:             # potentially faster DFS: The count has to be the same, so
                   1218:             # the order has to be the same, which DFS won't give us.
                   1219:             $args->{'currentJumpIndex'} = $counter;
                   1220:             $foundJump = 1;
                   1221:         }
                   1222:         
                   1223:         $curRes = $mapIterator->next();
                   1224:     }
                   1225: 
1.132     bowersj2 1226:     my $showParts = setDefault($args->{'showParts'}, 1);
                   1227:     my $condenseParts = setDefault($args->{'condenseParts'}, 1);
1.139     bowersj2 1228:     # keeps track of when the current resource is found,
                   1229:     # so we can back up a few and put the anchor above the
                   1230:     # current resource
1.140     bowersj2 1231:     my $printKey = $args->{'printKey'};
                   1232:     my $printCloseAll = $args->{'printCloseAll'};
                   1233:     if (!defined($printCloseAll)) { $printCloseAll = 1; }
1.144     bowersj2 1234:     
1.140     bowersj2 1235:     # Print key?
                   1236:     if ($printKey) {
                   1237:         $result .= '<table border="0" cellpadding="2" cellspacing="0">';
                   1238:         my $date=localtime;
                   1239:         $result.='<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>';
                   1240:         if ($navmap->{LAST_CHECK}) {
                   1241:             $result .= 
                   1242:                 '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
                   1243:                 strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
                   1244:                 '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
                   1245:                 '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
                   1246:                 '</td>'; 
                   1247:         } else {
                   1248:             $result .= '<td align="center" valign="bottom">&nbsp;&nbsp;'.
                   1249:                 '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
                   1250:                 '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
                   1251:                 '</td>'; 
                   1252:         }
                   1253: 
                   1254:         $result .= '</tr></table>';
                   1255:     }
                   1256: 
1.172     bowersj2 1257:     if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
1.140     bowersj2 1258:         if ($condition) {
                   1259:             $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
1.158     bowersj2 1260:                 "&here=" . Apache::lonnet::escape($here) .
1.140     bowersj2 1261:                 "\">Close All Folders</a>";
                   1262:         } else {
                   1263:             $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
1.158     bowersj2 1264:                 "&here=" . Apache::lonnet::escape($here) . 
1.140     bowersj2 1265:                 "\">Open All Folders</a>";
                   1266:         }
1.143     bowersj2 1267:         $result .= "<br /><br />\n";
1.140     bowersj2 1268:     }    
                   1269: 
                   1270:     if ($r) {
                   1271:         $r->print($result);
                   1272:         $r->rflush();
                   1273:         $result = "";
                   1274:     }
1.132     bowersj2 1275:     # End parameter setting
1.133     bowersj2 1276:             
1.132     bowersj2 1277:     # Data
1.140     bowersj2 1278:     $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
1.132     bowersj2 1279:     my $res = "Apache::lonnavmaps::resource";
                   1280:     my %condenseStatuses =
                   1281:         ( $res->NETWORK_FAILURE    => 1,
                   1282:           $res->NOTHING_SET        => 1,
                   1283:           $res->CORRECT            => 1 );
                   1284:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
1.133     bowersj2 1285: 
                   1286:     # Shared variables
                   1287:     $args->{'counter'} = 0; # counts the rows
                   1288:     $args->{'indentLevel'} = 0;
                   1289:     $args->{'isNewBranch'} = 0;
                   1290:     $args->{'condensed'} = 0;    
                   1291:     $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
                   1292:     $args->{'displayedHereMarker'} = 0;
1.132     bowersj2 1293: 
1.190     bowersj2 1294:     # If we're suppressing empty sequences, look for them here. Use DFS for speed,
                   1295:     # since structure actually doesn't matter, except what map has what resources.
                   1296:     if ($args->{'suppressEmptySequences'}) {
                   1297:         my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
                   1298:                                                          $it->{FIRST_RESOURCE},
                   1299:                                                          $it->{FINISH_RESOURCE},
                   1300:                                                          {}, undef, 1);
                   1301:         $depth = 0;
                   1302:         $dfsit->next();
                   1303:         my $curRes = $dfsit->next();
                   1304:         while ($depth > -1) {
                   1305:             if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
                   1306:             if ($curRes == $dfsit->END_MAP()) { $depth--; }
                   1307: 
                   1308:             if (ref($curRes)) { 
                   1309:                 # Parallel pre-processing: Do sequences have non-filtered-out children?
1.201     bowersj2 1310:                 if ($curRes->is_map()) {
1.190     bowersj2 1311:                     $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
                   1312:                     # Sequences themselves do not count as visible children,
                   1313:                     # unless those sequences also have visible children.
                   1314:                     # This means if a sequence appears, there's a "promise"
                   1315:                     # that there's something under it if you open it, somewhere.
                   1316:                 } else {
                   1317:                     # Not a sequence: if it's filtered, ignore it, otherwise
                   1318:                     # rise up the stack and mark the sequences as having children
                   1319:                     if (&$filterFunc($curRes)) {
                   1320:                         for my $sequence (@{$dfsit->getStack()}) {
                   1321:                             $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
                   1322:                         }
                   1323:                     }
                   1324:                 }
                   1325:             }
                   1326:         } continue {
                   1327:             $curRes = $dfsit->next();
                   1328:         }
                   1329:     }
                   1330: 
1.133     bowersj2 1331:     my $displayedJumpMarker = 0;
1.132     bowersj2 1332:     # Set up iteration.
1.159     bowersj2 1333:     $depth = 1;
1.132     bowersj2 1334:     $it->next(); # discard initial BEGIN_MAP
1.159     bowersj2 1335:     $curRes = $it->next();
1.132     bowersj2 1336:     my $now = time();
                   1337:     my $in24Hours = $now + 24 * 60 * 60;
                   1338:     my $rownum = 0;
                   1339: 
1.141     bowersj2 1340:     # export "here" marker information
                   1341:     $args->{'here'} = $here;
                   1342: 
1.132     bowersj2 1343:     while ($depth > 0) {
                   1344:         if ($curRes == $it->BEGIN_MAP()) { $depth++; }
                   1345:         if ($curRes == $it->END_MAP()) { $depth--; }
                   1346: 
                   1347:         # Maintain indentation level.
                   1348:         if ($curRes == $it->BEGIN_MAP() ||
                   1349:             $curRes == $it->BEGIN_BRANCH() ) {
1.133     bowersj2 1350:             $args->{'indentLevel'}++;
1.132     bowersj2 1351:         }
                   1352:         if ($curRes == $it->END_MAP() ||
                   1353:             $curRes == $it->END_BRANCH() ) {
1.133     bowersj2 1354:             $args->{'indentLevel'}--;
1.132     bowersj2 1355:         }
                   1356:         # Notice new branches
                   1357:         if ($curRes == $it->BEGIN_BRANCH()) {
1.133     bowersj2 1358:             $args->{'isNewBranch'} = 1;
                   1359:         }
                   1360: 
                   1361:         # If this isn't an actual resource, continue on
                   1362:         if (!ref($curRes)) {
                   1363:             next;
1.132     bowersj2 1364:         }
1.133     bowersj2 1365: 
1.143     bowersj2 1366:         # If this has been filtered out, continue on
                   1367:         if (!(&$filterFunc($curRes))) {
                   1368:             $args->{'isNewBranch'} = 0; # Don't falsely remember this
                   1369:             next;
                   1370:         } 
1.132     bowersj2 1371: 
1.190     bowersj2 1372:         # If this is an empty sequence and we're filtering them, continue on
1.201     bowersj2 1373:         if ($curRes->is_map() && $args->{'suppressEmptySequences'} &&
1.190     bowersj2 1374:             !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) {
                   1375:             next;
                   1376:         }
                   1377: 
1.153     bowersj2 1378:         # If we're suppressing navmaps and this is a navmap, continue on
                   1379:         if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
                   1380:             next;
                   1381:         }
                   1382: 
1.191     bowersj2 1383:         $args->{'counter'}++;
                   1384: 
1.132     bowersj2 1385:         # Does it have multiple parts?
1.133     bowersj2 1386:         $args->{'multipart'} = 0;
                   1387:         $args->{'condensed'} = 0;
1.132     bowersj2 1388:         my @parts;
                   1389:             
                   1390:         # Decide what parts to show.
1.133     bowersj2 1391:         if ($curRes->is_problem() && $showParts) {
1.132     bowersj2 1392:             @parts = @{$curRes->parts()};
1.192     bowersj2 1393:             $args->{'multipart'} = $curRes->multipart();
1.132     bowersj2 1394:             
                   1395:             if ($condenseParts) { # do the condensation
                   1396:                 if (!$curRes->opendate("0")) {
1.162     bowersj2 1397:                     @parts = ();
1.133     bowersj2 1398:                     $args->{'condensed'} = 1;
1.132     bowersj2 1399:                 }
1.133     bowersj2 1400:                 if (!$args->{'condensed'}) {
1.132     bowersj2 1401:                     # Decide whether to condense based on similarity
1.192     bowersj2 1402:                     my $status = $curRes->status($parts[0]);
                   1403:                     my $due = $curRes->duedate($parts[0]);
                   1404:                     my $open = $curRes->opendate($parts[0]);
1.132     bowersj2 1405:                     my $statusAllSame = 1;
                   1406:                     my $dueAllSame = 1;
                   1407:                     my $openAllSame = 1;
1.192     bowersj2 1408:                     for (my $i = 1; $i < scalar(@parts); $i++) {
1.132     bowersj2 1409:                         if ($curRes->status($parts[$i]) != $status){
                   1410:                             $statusAllSame = 0;
                   1411:                         }
                   1412:                         if ($curRes->duedate($parts[$i]) != $due ) {
                   1413:                             $dueAllSame = 0;
                   1414:                         }
                   1415:                         if ($curRes->opendate($parts[$i]) != $open) {
                   1416:                             $openAllSame = 0;
                   1417:                         }
                   1418:                     }
                   1419:                     # $*allSame is true if all the statuses were
                   1420:                     # the same. Now, if they are all the same and
                   1421:                     # match one of the statuses to condense, or they
                   1422:                     # are all open with the same due date, or they are
                   1423:                     # all OPEN_LATER with the same open date, display the
                   1424:                     # status of the first non-zero part (to get the 'correct'
                   1425:                     # status right, since 0 is never 'correct' or 'open').
                   1426:                     if (($statusAllSame && defined($condenseStatuses{$status})) ||
                   1427:                         ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
                   1428:                         ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
1.192     bowersj2 1429:                         @parts = ($parts[0]);
1.133     bowersj2 1430:                         $args->{'condensed'} = 1;
1.132     bowersj2 1431:                     }
                   1432:                 }
1.198     bowersj2 1433: 		# Multipart problem with one part: always "condense" (happens
                   1434: 		#  to match the desirable behavior)
                   1435: 		if ($curRes->countParts() == 1) {
                   1436: 		    @parts = ($parts[0]);
                   1437: 		    $args->{'condensed'} = 1;
                   1438: 		}
1.132     bowersj2 1439:             }
1.157     bowersj2 1440:         } 
1.132     bowersj2 1441:             
                   1442:         # If the multipart problem was condensed, "forget" it was multipart
                   1443:         if (scalar(@parts) == 1) {
1.133     bowersj2 1444:             $args->{'multipart'} = 0;
1.192     bowersj2 1445:         } else {
                   1446:             # Add part 0 so we display it correctly.
                   1447:             unshift @parts, '0';
1.132     bowersj2 1448:         }
                   1449: 
                   1450:         # Now, we've decided what parts to show. Loop through them and
                   1451:         # show them.
1.192     bowersj2 1452:         foreach my $part (@parts) {
1.132     bowersj2 1453:             $rownum ++;
                   1454:             my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
                   1455:             
                   1456:             $result .= "  <tr bgcolor='$backgroundColor'>\n";
1.134     bowersj2 1457: 
                   1458:             # Set up some data about the parts that the cols might want
                   1459:             my $filter = $it->{FILTER};
                   1460:             my $stack = $it->getStack();
                   1461:             my $src = getLinkForResource($stack);
                   1462:             
                   1463:             my $srcHasQuestion = $src =~ /\?/;
                   1464:             $args->{"resourceLink"} = $src.
                   1465:                 ($srcHasQuestion?'&':'?') .
1.137     bowersj2 1466:                 'symb=' . &Apache::lonnet::escape($curRes->symb());
1.132     bowersj2 1467:             
                   1468:             # Now, display each column.
                   1469:             foreach my $col (@$cols) {
1.139     bowersj2 1470:                 my $colHTML = '';
                   1471:                 if (ref($col)) {
                   1472:                     $colHTML .= &$col($curRes, $part, $args);
                   1473:                 } else {
                   1474:                     $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
                   1475:                 }
1.132     bowersj2 1476: 
1.133     bowersj2 1477:                 # If this is the first column and it's time to print
                   1478:                 # the anchor, do so
                   1479:                 if ($col == $cols->[0] && 
                   1480:                     $args->{'counter'} == $args->{'currentJumpIndex'} - 
1.139     bowersj2 1481:                     $currentJumpDelta) {
                   1482:                     # Jam the anchor after the <td> tag;
                   1483:                     # necessary for valid HTML (which Mozilla requires)
                   1484:                     $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
1.133     bowersj2 1485:                     $displayedJumpMarker = 1;
                   1486:                 }
1.139     bowersj2 1487:                 $result .= $colHTML . "\n";
1.132     bowersj2 1488:             }
1.139     bowersj2 1489:             $result .= "    </tr>\n";
1.140     bowersj2 1490:             $args->{'isNewBranch'} = 0;
1.139     bowersj2 1491:         }
1.153     bowersj2 1492: 
1.139     bowersj2 1493:         if ($r && $rownum % 20 == 0) {
                   1494:             $r->print($result);
                   1495:             $result = "";
                   1496:             $r->rflush();
1.132     bowersj2 1497:         }
1.156     bowersj2 1498:     } continue {
1.132     bowersj2 1499:         $curRes = $it->next();
                   1500:     }
                   1501:     
1.134     bowersj2 1502:     # Print out the part that jumps to #curloc if it exists
1.159     bowersj2 1503:     # delay needed because the browser is processing the jump before
                   1504:     # it finishes rendering, so it goes to the wrong place!
                   1505:     # onload might be better, but this routine has no access to that.
                   1506:     # On mozilla, the 0-millisecond timeout seems to prevent this;
                   1507:     # it's quite likely this might fix other browsers, too, and 
                   1508:     # certainly won't hurt anything.
1.139     bowersj2 1509:     if ($displayedJumpMarker) {
1.159     bowersj2 1510:         $result .= "<script>setTimeout(\"location += '#curloc';\", 0)</script>\n";
1.134     bowersj2 1511:     }
                   1512: 
1.132     bowersj2 1513:     $result .= "</table>";
1.140     bowersj2 1514:     
                   1515:     if ($r) {
                   1516:         $r->print($result);
                   1517:         $result = "";
                   1518:         $r->rflush();
                   1519:     }
                   1520:         
1.175     bowersj2 1521:     if ($mustCloseNavMap) { $navmap->untieHashes(); } 
1.132     bowersj2 1522: 
                   1523:     return $result;
                   1524: }
                   1525: 
1.133     bowersj2 1526: 1;
                   1527: 
                   1528: package Apache::lonnavmaps::navmap;
                   1529: 
                   1530: =pod
                   1531: 
1.174     albertel 1532: lonnavmaps provides functions and objects for dealing with the
                   1533: compiled course hashes generated when a user enters the course, the
                   1534: Apache handler for the "Navigation Map" button, and a flexible
                   1535: prepared renderer for navigation maps that are easy to use anywhere.
                   1536: 
                   1537: =head1 Object: navmap
1.133     bowersj2 1538: 
1.174     albertel 1539: Encapsulating the compiled nav map
1.133     bowersj2 1540: 
1.174     albertel 1541: navmap is an object that encapsulates a compiled course map and
                   1542: provides a reasonable interface to it.
1.133     bowersj2 1543: 
1.174     albertel 1544: Most notably it provides a way to navigate the map sensibly and a
                   1545: flexible iterator that makes it easy to write various renderers based
                   1546: on nav maps.
1.133     bowersj2 1547: 
                   1548: You must obtain resource objects through the navmap object.
                   1549: 
                   1550: =head2 Methods
                   1551: 
                   1552: =over 4
                   1553: 
1.174     albertel 1554: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions,
                   1555:   genMailDiscussStatus):
1.133     bowersj2 1556: 
1.174     albertel 1557: Binds a new navmap object to the compiled nav map hash and parm hash
                   1558: given as filenames. genCourseAndUserOptions is a flag saying whether
                   1559: the course options and user options hash should be generated. This is
                   1560: for when you are using the parameters of the resources that require
                   1561: them; see documentation in resource object
                   1562: documentation. genMailDiscussStatus causes the nav map to retreive
                   1563: information about the email and discussion status of
                   1564: resources. Returns the navmap object if this is successful, or
                   1565: B<undef> if not. You must check for undef; errors will occur when you
                   1566: try to use the other methods otherwise.
                   1567: 
                   1568: =item * B<getIterator>(first, finish, filter, condition):
                   1569: 
                   1570: See iterator documentation below.
1.133     bowersj2 1571: 
                   1572: =cut
                   1573: 
                   1574: use strict;
                   1575: use GDBM_File;
                   1576: 
                   1577: sub new {
                   1578:     # magic invocation to create a class instance
                   1579:     my $proto = shift;
                   1580:     my $class = ref($proto) || $proto;
                   1581:     my $self = {};
                   1582: 
                   1583:     $self->{NAV_HASH_FILE} = shift;
                   1584:     $self->{PARM_HASH_FILE} = shift;
                   1585:     $self->{GENERATE_COURSE_USER_OPT} = shift;
                   1586:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
                   1587: 
                   1588:     # Resource cache stores navmap resources as we reference them. We generate
                   1589:     # them on-demand so we don't pay for creating resources unless we use them.
                   1590:     $self->{RESOURCE_CACHE} = {};
                   1591: 
                   1592:     # Network failure flag, if we accessed the course or user opt and
                   1593:     # failed
                   1594:     $self->{NETWORK_FAILURE} = 0;
                   1595: 
                   1596:     # tie the nav hash
                   1597: 
1.168     bowersj2 1598:     my %navmaphash;
                   1599:     my %parmhash;
                   1600:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
1.133     bowersj2 1601:               &GDBM_READER(), 0640))) {
                   1602:         return undef;
                   1603:     }
                   1604:     
1.168     bowersj2 1605:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
1.133     bowersj2 1606:               &GDBM_READER(), 0640)))
                   1607:     {
1.170     matthew  1608:         untie %{$self->{PARM_HASH}};
1.133     bowersj2 1609:         return undef;
                   1610:     }
                   1611: 
1.199     bowersj2 1612:     $self->{NAV_HASH} = \%navmaphash;
1.168     bowersj2 1613:     $self->{PARM_HASH} = \%parmhash;
1.140     bowersj2 1614:     $self->{INITED} = 0;
1.133     bowersj2 1615: 
                   1616:     bless($self);
                   1617:         
                   1618:     return $self;
                   1619: }
                   1620: 
                   1621: sub init {
                   1622:     my $self = shift;
1.140     bowersj2 1623:     if ($self->{INITED}) { return; }
1.133     bowersj2 1624: 
                   1625:     # If the course opt hash and the user opt hash should be generated,
                   1626:     # generate them
                   1627:     if ($self->{GENERATE_COURSE_USER_OPT}) {
                   1628:         my $uname=$ENV{'user.name'};
                   1629:         my $udom=$ENV{'user.domain'};
                   1630:         my $uhome=$ENV{'user.home'};
                   1631:         my $cid=$ENV{'request.course.id'};
                   1632:         my $chome=$ENV{'course.'.$cid.'.home'};
                   1633:         my ($cdom,$cnum)=split(/\_/,$cid);
                   1634:         
                   1635:         my $userprefix=$uname.'_'.$udom.'_';
                   1636:         
                   1637:         my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
                   1638:         unless ($uhome eq 'no_host') { 
                   1639: # ------------------------------------------------- Get coursedata (if present)
                   1640:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
                   1641:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
                   1642:                                                  ':resourcedata',$chome);
1.182     bowersj2 1643:                 # Check for network failure
                   1644:                 if ( $reply =~ /no.such.host/i || $reply =~ /con_lost/i) {
                   1645:                     $self->{NETWORK_FAILURE} = 1;
                   1646:                 } elsif ($reply!~/^error\:/) {
1.133     bowersj2 1647:                     $courserdatas{$cid}=$reply;
                   1648:                     $courserdatas{$cid.'.last_cache'}=time;
                   1649:                 }
                   1650:             }
                   1651:             foreach (split(/\&/,$courserdatas{$cid})) {
                   1652:                 my ($name,$value)=split(/\=/,$_);
                   1653:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
                   1654:                     &Apache::lonnet::unescape($value);
                   1655:             }
                   1656: # --------------------------------------------------- Get userdata (if present)
                   1657:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
                   1658:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
                   1659:                 if ($reply!~/^error\:/) {
                   1660:                     $userrdatas{$uname.'___'.$udom}=$reply;
                   1661:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
                   1662:                 }
                   1663:                 # check to see if network failed
                   1664:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
                   1665:                 {
                   1666:                     $self->{NETWORK_FAILURE} = 1;
                   1667:                 }
                   1668:             }
                   1669:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
                   1670:                 my ($name,$value)=split(/\=/,$_);
                   1671:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
                   1672:                     &Apache::lonnet::unescape($value);
                   1673:             }
                   1674:             $self->{COURSE_OPT} = \%courseopt;
                   1675:             $self->{USER_OPT} = \%useropt;
                   1676:         }
                   1677:     }   
                   1678: 
                   1679:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
                   1680:         my $cid=$ENV{'request.course.id'};
                   1681:         my ($cdom,$cnum)=split(/\_/,$cid);
                   1682:         
                   1683:         my %emailstatus = &Apache::lonnet::dump('email_status');
                   1684:         my $logoutTime = $emailstatus{'logout'};
                   1685:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
1.193     bowersj2 1686:         $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
1.133     bowersj2 1687:                                $courseLeaveTime : $logoutTime);
                   1688:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
                   1689:                                                    $cdom, $cnum);
                   1690:         my %feedback=();
                   1691:         my %error=();
                   1692:         my $keys = &Apache::lonnet::reply('keys:'.
                   1693:                                           $ENV{'user.domain'}.':'.
                   1694:                                           $ENV{'user.name'}.':nohist_email',
                   1695:                                           $ENV{'user.home'});
                   1696: 
                   1697:         foreach my $msgid (split(/\&/, $keys)) {
                   1698:             $msgid=&Apache::lonnet::unescape($msgid);
                   1699:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
                   1700:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
                   1701:                 my ($what,$url)=($1,$2);
                   1702:                 my %status=
                   1703:                     &Apache::lonnet::get('email_status',[$msgid]);
                   1704:                 if ($status{$msgid}=~/^error\:/) { 
                   1705:                     $status{$msgid}=''; 
                   1706:                 }
                   1707:                 
                   1708:                 if (($status{$msgid} eq 'new') || 
                   1709:                     (!$status{$msgid})) { 
                   1710:                     if ($what eq 'Error') {
                   1711:                         $error{$url}.=','.$msgid; 
                   1712:                     } else {
                   1713:                         $feedback{$url}.=','.$msgid;
                   1714:                     }
                   1715:                 }
                   1716:             }
                   1717:         }
                   1718:         
                   1719:         $self->{FEEDBACK} = \%feedback;
                   1720:         $self->{ERROR_MSG} = \%error; # what is this? JB
                   1721:         $self->{DISCUSSION_TIME} = \%discussiontime;
                   1722:         $self->{EMAIL_STATUS} = \%emailstatus;
                   1723:         
                   1724:     }    
                   1725: 
                   1726:     $self->{PARM_CACHE} = {};
1.140     bowersj2 1727:     $self->{INITED} = 1;
1.133     bowersj2 1728: }
                   1729: 
                   1730: # Internal function: Takes a key to look up in the nav hash and implements internal
                   1731: # memory caching of that key.
                   1732: sub navhash {
                   1733:     my $self = shift; my $key = shift;
                   1734:     return $self->{NAV_HASH}->{$key};
                   1735: }
                   1736: 
                   1737: # Checks to see if coursemap is defined, matching test in old lonnavmaps
                   1738: sub courseMapDefined {
                   1739:     my $self = shift;
                   1740:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
                   1741: 
                   1742:     my $firstres = $self->navhash("map_start_$uri");
                   1743:     my $lastres = $self->navhash("map_finish_$uri");
                   1744:     return $firstres && $lastres;
                   1745: }
                   1746: 
                   1747: sub getIterator {
                   1748:     my $self = shift;
                   1749:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
                   1750:                                                      shift, undef, shift);
                   1751:     return $iterator;
                   1752: }
                   1753: 
                   1754: # unties the hash when done
                   1755: sub untieHashes {
1.168     bowersj2 1756:     my $self = shift;
1.170     matthew  1757:     untie %{$self->{NAV_HASH}};
                   1758:     untie %{$self->{PARM_HASH}};
1.133     bowersj2 1759: }
                   1760: 
                   1761: # Private method: Does the given resource (as a symb string) have
                   1762: # current discussion? Returns 0 if chat/mail data not extracted.
                   1763: sub hasDiscussion {
                   1764:     my $self = shift;
                   1765:     my $symb = shift;
                   1766:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
                   1767: 
                   1768:     #return defined($self->{DISCUSSION_TIME}->{$symb});
                   1769:     return $self->{DISCUSSION_TIME}->{$symb} >
                   1770:            $self->{LAST_CHECK};
                   1771: }
                   1772: 
                   1773: # Private method: Does the given resource (as a symb string) have
                   1774: # current feedback? Returns the string in the feedback hash, which
                   1775: # will be false if it does not exist.
                   1776: sub getFeedback { 
                   1777:     my $self = shift;
                   1778:     my $symb = shift;
                   1779: 
                   1780:     if (!defined($self->{FEEDBACK})) { return ""; }
                   1781:     
                   1782:     return $self->{FEEDBACK}->{$symb};
                   1783: }
                   1784: 
                   1785: # Private method: Get the errors for that resource (by source).
                   1786: sub getErrors { 
                   1787:     my $self = shift;
                   1788:     my $src = shift;
                   1789:     
                   1790:     if (!defined($self->{ERROR_MSG})) { return ""; }
                   1791:     return $self->{ERROR_MSG}->{$src};
                   1792: }
                   1793: 
                   1794: =pod
                   1795: 
1.174     albertel 1796: =item * B<getById>(id):
                   1797: 
                   1798: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
                   1799: object for that resource. This method, or other methods that use it
                   1800: (as in the resource object) is the only proper way to obtain a
                   1801: resource object.
1.133     bowersj2 1802: 
1.194     bowersj2 1803: =item * B<getBySymb>(symb):
                   1804: 
                   1805: Based on the symb of the resource, get a resource object for that
                   1806: resource. This is one of the proper ways to get a resource object.
                   1807: 
                   1808: =item * B<getMapByMapPc>(map_pc):
                   1809: 
                   1810: Based on the map_pc of the resource, get a resource object for
                   1811: the given map. This is one of the proper ways to get a resource object.
                   1812: 
1.133     bowersj2 1813: =cut
                   1814: 
                   1815: # The strategy here is to cache the resource objects, and only construct them
                   1816: # as we use them. The real point is to prevent reading any more from the tied
                   1817: # hash then we have to, which should hopefully alleviate speed problems.
                   1818: # Caching is just an incidental detail I throw in because it makes sense.
                   1819: 
                   1820: sub getById {
                   1821:     my $self = shift;
                   1822:     my $id = shift;
                   1823: 
                   1824:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
                   1825:     {
                   1826:         return $self->{RESOURCE_CACHE}->{$id};
                   1827:     }
                   1828: 
                   1829:     # resource handles inserting itself into cache.
                   1830:     # Not clear why the quotes are necessary, but as of this
                   1831:     # writing it doesn't work without them.
                   1832:     return "Apache::lonnavmaps::resource"->new($self, $id);
1.132     bowersj2 1833: }
1.133     bowersj2 1834: 
1.172     bowersj2 1835: sub getBySymb {
                   1836:     my $self = shift;
                   1837:     my $symb = shift;
                   1838:     my ($mapUrl, $id, $filename) = split (/___/, $symb);
                   1839:     my $map = $self->getResourceByUrl($mapUrl);
                   1840:     return $self->getById($map->map_pc() . '.' . $id);
1.194     bowersj2 1841: }
                   1842: 
                   1843: sub getByMapPc {
                   1844:     my $self = shift;
                   1845:     my $map_pc = shift;
                   1846:     my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
                   1847:     $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
                   1848:     return $self->getById($map_id);
1.172     bowersj2 1849: }
                   1850: 
1.133     bowersj2 1851: =pod
                   1852: 
1.174     albertel 1853: =item * B<firstResource>():
                   1854: 
                   1855: Returns a resource object reference corresponding to the first
                   1856: resource in the navmap.
1.133     bowersj2 1857: 
                   1858: =cut
                   1859: 
                   1860: sub firstResource {
                   1861:     my $self = shift;
                   1862:     my $firstResource = $self->navhash('map_start_' .
                   1863:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
                   1864:     return $self->getById($firstResource);
1.132     bowersj2 1865: }
1.133     bowersj2 1866: 
                   1867: =pod
                   1868: 
1.174     albertel 1869: =item * B<finishResource>():
                   1870: 
                   1871: Returns a resource object reference corresponding to the last resource
                   1872: in the navmap.
1.133     bowersj2 1873: 
                   1874: =cut
                   1875: 
                   1876: sub finishResource {
                   1877:     my $self = shift;
                   1878:     my $firstResource = $self->navhash('map_finish_' .
                   1879:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
                   1880:     return $self->getById($firstResource);
1.132     bowersj2 1881: }
1.133     bowersj2 1882: 
                   1883: # Parmval reads the parm hash and cascades the lookups. parmval_real does
                   1884: # the actual lookup; parmval caches the results.
                   1885: sub parmval {
                   1886:     my $self = shift;
                   1887:     my ($what,$symb)=@_;
                   1888:     my $hashkey = $what."|||".$symb;
                   1889: 
                   1890:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
                   1891:         return $self->{PARM_CACHE}->{$hashkey};
                   1892:     }
                   1893: 
                   1894:     my $result = $self->parmval_real($what, $symb);
                   1895:     $self->{PARM_CACHE}->{$hashkey} = $result;
                   1896:     return $result;
1.132     bowersj2 1897: }
                   1898: 
1.133     bowersj2 1899: sub parmval_real {
                   1900:     my $self = shift;
                   1901:     my ($what,$symb) = @_;
                   1902: 
                   1903:     my $cid=$ENV{'request.course.id'};
                   1904:     my $csec=$ENV{'request.course.sec'};
                   1905:     my $uname=$ENV{'user.name'};
                   1906:     my $udom=$ENV{'user.domain'};
                   1907: 
                   1908:     unless ($symb) { return ''; }
                   1909:     my $result='';
                   1910: 
                   1911:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
                   1912: 
                   1913: # ----------------------------------------------------- Cascading lookup scheme
                   1914:     my $rwhat=$what;
                   1915:     $what=~s/^parameter\_//;
                   1916:     $what=~s/\_/\./;
                   1917: 
                   1918:     my $symbparm=$symb.'.'.$what;
                   1919:     my $mapparm=$mapname.'___(all).'.$what;
                   1920:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
                   1921: 
                   1922:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
                   1923:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
                   1924:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
                   1925: 
                   1926:     my $courselevel= $usercourseprefix.'.'.$what;
                   1927:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
                   1928:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
                   1929: 
                   1930:     my $useropt = $self->{USER_OPT};
                   1931:     my $courseopt = $self->{COURSE_OPT};
                   1932:     my $parmhash = $self->{PARM_HASH};
                   1933: 
                   1934: # ---------------------------------------------------------- first, check user
                   1935:     if ($uname and defined($useropt)) {
                   1936:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
                   1937:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
                   1938:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
                   1939:     }
                   1940: 
                   1941: # ------------------------------------------------------- second, check course
                   1942:     if ($csec and defined($courseopt)) {
                   1943:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
                   1944:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
                   1945:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
                   1946:     }
                   1947: 
                   1948:     if (defined($courseopt)) {
                   1949:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
                   1950:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
                   1951:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
                   1952:     }
                   1953: 
                   1954: # ----------------------------------------------------- third, check map parms
                   1955: 
                   1956:     my $thisparm=$$parmhash{$symbparm};
                   1957:     if (defined($thisparm)) { return $thisparm; }
                   1958: 
                   1959: # ----------------------------------------------------- fourth , check default
                   1960: 
                   1961:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
                   1962:     if (defined($default)) { return $default}
                   1963: 
                   1964: # --------------------------------------------------- fifth , cascade up parts
                   1965: 
                   1966:     my ($space,@qualifier)=split(/\./,$rwhat);
                   1967:     my $qualifier=join('.',@qualifier);
                   1968:     unless ($space eq '0') {
1.160     albertel 1969: 	my @parts=split(/_/,$space);
                   1970: 	my $id=pop(@parts);
                   1971: 	my $part=join('_',@parts);
                   1972: 	if ($part eq '') { $part='0'; }
                   1973: 	my $partgeneral=$self->parmval($part.".$qualifier",$symb);
                   1974: 	if (defined($partgeneral)) { return $partgeneral; }
1.133     bowersj2 1975:     }
                   1976:     return '';
1.145     bowersj2 1977: }
                   1978: 
1.174     albertel 1979: =pod
1.145     bowersj2 1980: 
1.174     albertel 1981: =item * B<getResourceByUrl>(url):
1.145     bowersj2 1982: 
1.174     albertel 1983: Retrieves a resource object by URL of the resource. If passed a
                   1984: resource object, it will simply return it, so it is safe to use this
                   1985: method in code like "$res = $navmap->getResourceByUrl($res)", if
                   1986: you're not sure if $res is already an object, or just a URL. If the
                   1987: resource appears multiple times in the course, only the first instance
                   1988: will be returned. As a result, this is probably useful only for maps.
                   1989: 
                   1990: =item * B<retrieveResources>(map, filterFunc, recursive, bailout):
                   1991: 
                   1992: The map is a specification of a map to retreive the resources from,
                   1993: either as a url or as an object. The filterFunc is a reference to a
                   1994: function that takes a resource object as its one argument and returns
                   1995: true if the resource should be included, or false if it should not
                   1996: be. If recursive is true, the map will be recursively examined,
                   1997: otherwise it will not be. If bailout is true, the function will return
                   1998: as soon as it finds a resource, if false it will finish. By default,
                   1999: the map is the top-level map of the course, filterFunc is a function
                   2000: that always returns 1, recursive is true, bailout is false. The
                   2001: resources will be returned in a list containing the resource objects
                   2002: for the corresponding resources, with B<no structure information> in
                   2003: the list; regardless of branching, recursion, etc., it will be a flat
                   2004: list.
                   2005: 
                   2006: Thus, this is suitable for cases where you don't want the structure,
                   2007: just a list of all resources. It is also suitable for finding out how
                   2008: many resources match a given description; for this use, if all you
                   2009: want to know is if I<any> resources match the description, the bailout
                   2010: parameter will allow you to avoid potentially expensive enumeration of
                   2011: all matching resources.
1.145     bowersj2 2012: 
1.174     albertel 2013: =item * B<hasResources>(map, filterFunc, recursive):
1.145     bowersj2 2014: 
1.174     albertel 2015: Convience method for
1.146     bowersj2 2016: 
                   2017:  scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
                   2018: 
1.174     albertel 2019: which will tell whether the map has resources matching the description
                   2020: in the filter function.
1.146     bowersj2 2021: 
1.145     bowersj2 2022: =cut
                   2023: 
                   2024: sub getResourceByUrl {
                   2025:     my $self = shift;
                   2026:     my $resUrl = shift;
                   2027: 
                   2028:     if (ref($resUrl)) { return $resUrl; }
                   2029: 
                   2030:     $resUrl = &Apache::lonnet::clutter($resUrl);
                   2031:     my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
                   2032:     if ($resId =~ /,/) {
                   2033:         $resId = (split (/,/, $resId))[0];
                   2034:     }
                   2035:     if (!$resId) { return ''; }
                   2036:     return $self->getById($resId);
                   2037: }
                   2038: 
                   2039: sub retrieveResources {
                   2040:     my $self = shift;
                   2041:     my $map = shift;
                   2042:     my $filterFunc = shift;
                   2043:     if (!defined ($filterFunc)) {
                   2044:         $filterFunc = sub {return 1;};
                   2045:     }
                   2046:     my $recursive = shift;
                   2047:     if (!defined($recursive)) { $recursive = 1; }
                   2048:     my $bailout = shift;
                   2049:     if (!defined($bailout)) { $bailout = 0; }
                   2050: 
                   2051:     # Create the necessary iterator.
                   2052:     if (!ref($map)) { # assume it's a url of a map.
1.172     bowersj2 2053:         $map = $self->getResourceByUrl($map);
1.145     bowersj2 2054:     }
                   2055: 
                   2056:     # Check the map's validity.
                   2057:     if (!$map || !$map->is_map()) {
                   2058:         # Oh, to throw an exception.... how I'd love that!
                   2059:         return ();
                   2060:     }
                   2061: 
1.146     bowersj2 2062:     # Get an iterator.
                   2063:     my $it = $self->getIterator($map->map_start(), $map->map_finish(),
                   2064:                                 !$recursive);
                   2065: 
                   2066:     my @resources = ();
                   2067: 
                   2068:     # Run down the iterator and collect the resources.
                   2069:     my $depth = 1;
                   2070:     $it->next();
                   2071:     my $curRes = $it->next();
                   2072: 
                   2073:     while ($depth > 0) {
                   2074:         if ($curRes == $it->BEGIN_MAP()) {
                   2075:             $depth++;
                   2076:         }
                   2077:         if ($curRes == $it->END_MAP()) {
                   2078:             $depth--;
                   2079:         }
                   2080:         
                   2081:         if (ref($curRes)) {
                   2082:             if (!&$filterFunc($curRes)) {
                   2083:                 next;
                   2084:             }
                   2085: 
                   2086:             push @resources, $curRes;
                   2087: 
                   2088:             if ($bailout) {
                   2089:                 return @resources;
                   2090:             }
                   2091:         }
                   2092: 
                   2093:         $curRes = $it->next();
                   2094:     }
                   2095: 
                   2096:     return @resources;
                   2097: }
                   2098: 
                   2099: sub hasResource {
                   2100:     my $self = shift;
                   2101:     my $map = shift;
                   2102:     my $filterFunc = shift;
                   2103:     my $recursive = shift;
                   2104:     
                   2105:     return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
1.133     bowersj2 2106: }
1.51      bowersj2 2107: 
                   2108: 1;
                   2109: 
                   2110: package Apache::lonnavmaps::iterator;
                   2111: 
                   2112: =pod
                   2113: 
                   2114: =back
                   2115: 
1.174     albertel 2116: =head1 Object: navmap Iterator
1.51      bowersj2 2117: 
1.174     albertel 2118: An I<iterator> encapsulates the logic required to traverse a data
                   2119: structure. navmap uses an iterator to traverse the course map
                   2120: according to the criteria you wish to use.
                   2121: 
                   2122: To obtain an iterator, call the B<getIterator>() function of a
                   2123: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
                   2124: directly.) This will return a reference to the iterator:
1.51      bowersj2 2125: 
                   2126: C<my $resourceIterator = $navmap-E<gt>getIterator();>
                   2127: 
                   2128: To get the next thing from the iterator, call B<next>:
                   2129: 
                   2130: C<my $nextThing = $resourceIterator-E<gt>next()>
                   2131: 
                   2132: getIterator behaves as follows:
                   2133: 
                   2134: =over 4
                   2135: 
1.174     albertel 2136: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
                   2137: 
                   2138: All parameters are optional. firstResource is a resource reference
                   2139: corresponding to where the iterator should start. It defaults to
                   2140: navmap->firstResource() for the corresponding nav map. finishResource
                   2141: corresponds to where you want the iterator to end, defaulting to
                   2142: navmap->finishResource(). filterHash is a hash used as a set
                   2143: containing strings representing the resource IDs, defaulting to
                   2144: empty. Condition is a 1 or 0 that sets what to do with the filter
1.205   ! bowersj2 2145: hash: If a 0, then only resources that exist IN the filterHash will be
1.174     albertel 2146: recursed on. If it is a 1, only resources NOT in the filterHash will
                   2147: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
                   2148: false (default), the iterator will only return the first level of map
                   2149: that is not just a single, 'redirecting' map. If true, the iterator
                   2150: will return all information, starting with the top-level map,
                   2151: regardless of content. returnTopMap, if true (default false), will
                   2152: cause the iterator to return the top-level map object (resource 0.0)
                   2153: before anything else.
                   2154: 
                   2155: Thus, by default, only top-level resources will be shown. Change the
                   2156: condition to a 1 without changing the hash, and all resources will be
                   2157: shown. Changing the condition to 1 and including some values in the
                   2158: hash will allow you to selectively suppress parts of the navmap, while
                   2159: leaving it on 0 and adding things to the hash will allow you to
                   2160: selectively add parts of the nav map. See the handler code for
                   2161: examples.
                   2162: 
                   2163: The iterator will return either a reference to a resource object, or a
                   2164: token representing something in the map, such as the beginning of a
                   2165: new branch. The possible tokens are:
                   2166: 
                   2167: =over 4
1.51      bowersj2 2168: 
1.174     albertel 2169: =item * BEGIN_MAP:
1.51      bowersj2 2170: 
1.174     albertel 2171: A new map is being recursed into. This is returned I<after> the map
                   2172: resource itself is returned.
1.51      bowersj2 2173: 
1.174     albertel 2174: =item * END_MAP:
                   2175: 
                   2176: The map is now done.
1.51      bowersj2 2177: 
1.174     albertel 2178: =item * BEGIN_BRANCH:
1.70      bowersj2 2179: 
1.174     albertel 2180: A branch is now starting. The next resource returned will be the first
                   2181: in that branch.
1.70      bowersj2 2182: 
1.174     albertel 2183: =item * END_BRANCH:
1.70      bowersj2 2184: 
1.174     albertel 2185: The branch is now done.
1.51      bowersj2 2186: 
                   2187: =back
                   2188: 
1.174     albertel 2189: The tokens are retreivable via methods on the iterator object, i.e.,
                   2190: $iterator->END_MAP.
1.70      bowersj2 2191: 
1.174     albertel 2192: Maps can contain empty resources. The iterator will automatically skip
                   2193: over such resources, but will still treat the structure
                   2194: correctly. Thus, a complicated map with several branches, but
                   2195: consisting entirely of empty resources except for one beginning or
                   2196: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
                   2197: but only one resource will be returned.
1.116     bowersj2 2198: 
1.70      bowersj2 2199: =back
1.51      bowersj2 2200: 
                   2201: =cut
                   2202: 
                   2203: # Here are the tokens for the iterator:
                   2204: 
                   2205: sub BEGIN_MAP { return 1; }    # begining of a new map
                   2206: sub END_MAP { return 2; }      # end of the map
                   2207: sub BEGIN_BRANCH { return 3; } # beginning of a branch
                   2208: sub END_BRANCH { return 4; }   # end of a branch
1.89      bowersj2 2209: sub FORWARD { return 1; }      # go forward
                   2210: sub BACKWARD { return 2; }
1.51      bowersj2 2211: 
1.96      bowersj2 2212: sub min {
                   2213:     (my $a, my $b) = @_;
                   2214:     if ($a < $b) { return $a; } else { return $b; }
                   2215: }
                   2216: 
1.107     bowersj2 2217: # In the CVS repository, documentation of this algorithm is included 
                   2218: # in /doc/lonnavdocs, as a PDF and .tex source. Markers like **1**
                   2219: # will reference the same location in the text as the part of the
                   2220: # algorithm is running through.
                   2221: 
1.94      bowersj2 2222: sub new {
                   2223:     # magic invocation to create a class instance
                   2224:     my $proto = shift;
                   2225:     my $class = ref($proto) || $proto;
                   2226:     my $self = {};
                   2227: 
                   2228:     $self->{NAV_MAP} = shift;
                   2229:     return undef unless ($self->{NAV_MAP});
                   2230: 
                   2231:     # Handle the parameters
                   2232:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
                   2233:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
                   2234: 
                   2235:     # If the given resources are just the ID of the resource, get the
                   2236:     # objects
                   2237:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
                   2238:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
                   2239:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
                   2240:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
                   2241: 
                   2242:     $self->{FILTER} = shift;
                   2243: 
                   2244:     # A hash, used as a set, of resource already seen
                   2245:     $self->{ALREADY_SEEN} = shift;
                   2246:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
                   2247:     $self->{CONDITION} = shift;
                   2248: 
1.116     bowersj2 2249:     # Do we want to automatically follow "redirection" maps?
                   2250:     $self->{FORCE_TOP} = shift;
                   2251: 
1.162     bowersj2 2252:     # Do we want to return the top-level map object (resource 0.0)?
                   2253:     $self->{RETURN_0} = shift;
                   2254:     # have we done that yet?
                   2255:     $self->{HAVE_RETURNED_0} = 0;
                   2256: 
1.94      bowersj2 2257:     # Now, we need to pre-process the map, by walking forward and backward
                   2258:     # over the parts of the map we're going to look at.
1.96      bowersj2 2259: 
1.97      bowersj2 2260:     # The processing steps are exactly the same, except for a few small 
                   2261:     # changes, so I bundle those up in the following list of two elements:
                   2262:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
                   2263:     # first_resource).
                   2264:     # This prevents writing nearly-identical code twice.
                   2265:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
                   2266:                         'FIRST_RESOURCE'],
                   2267:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
                   2268:                         'FINISH_RESOURCE'] );
                   2269: 
1.98      bowersj2 2270:     my $maxDepth = 0; # tracks max depth
                   2271: 
1.116     bowersj2 2272:     # If there is only one resource in this map, and it's a map, we
                   2273:     # want to remember that, so the user can ask for the first map
                   2274:     # that isn't just a redirector.
                   2275:     my $resource; my $resourceCount = 0;
                   2276: 
1.107     bowersj2 2277:     # **1**
                   2278: 
1.97      bowersj2 2279:     foreach my $pass (@iterations) {
                   2280:         my $direction = $pass->[0];
                   2281:         my $valName = $pass->[1];
                   2282:         my $nextResourceMethod = $pass->[2];
                   2283:         my $firstResourceName = $pass->[3];
                   2284: 
                   2285:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
                   2286:                                                             $self->{FIRST_RESOURCE},
                   2287:                                                             $self->{FINISH_RESOURCE},
                   2288:                                                             {}, undef, 0, $direction);
1.96      bowersj2 2289:     
1.97      bowersj2 2290:         # prime the recursion
                   2291:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
1.98      bowersj2 2292:         my $depth = 0;
1.97      bowersj2 2293:         $iterator->next();
                   2294:         my $curRes = $iterator->next();
1.98      bowersj2 2295:         while ($depth > -1) {
1.97      bowersj2 2296:             if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
                   2297:             if ($curRes == $iterator->END_MAP()) { $depth--; }
1.96      bowersj2 2298:         
1.97      bowersj2 2299:             if (ref($curRes)) {
1.116     bowersj2 2300:                 # If there's only one resource, this will save it
1.117     bowersj2 2301:                 # we have to filter empty resources from consideration here,
                   2302:                 # or even "empty", redirecting maps have two (start & finish)
                   2303:                 # or three (start, finish, plus redirector)
                   2304:                 if($direction == FORWARD && $curRes->src()) { 
                   2305:                     $resource = $curRes; $resourceCount++; 
                   2306:                 }
1.97      bowersj2 2307:                 my $resultingVal = $curRes->{DATA}->{$valName};
                   2308:                 my $nextResources = $curRes->$nextResourceMethod();
1.116     bowersj2 2309:                 my $nextCount = scalar(@{$nextResources});
1.104     bowersj2 2310: 
1.116     bowersj2 2311:                 if ($nextCount == 1) { # **3**
1.97      bowersj2 2312:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
                   2313:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
                   2314:                 }
                   2315:                 
1.116     bowersj2 2316:                 if ($nextCount > 1) { # **4**
1.97      bowersj2 2317:                     foreach my $res (@{$nextResources}) {
                   2318:                         my $current = $res->{DATA}->{$valName} || 999999999;
                   2319:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
                   2320:                     }
                   2321:                 }
                   2322:             }
1.96      bowersj2 2323:             
1.107     bowersj2 2324:             # Assign the final val (**2**)
1.97      bowersj2 2325:             if (ref($curRes) && $direction == BACKWARD()) {
1.98      bowersj2 2326:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
                   2327:                                      $curRes->{DATA}->{BOT_UP_VAL});
                   2328:                 
                   2329:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
                   2330:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
1.190     bowersj2 2331:             }
                   2332:         } continue {
1.97      bowersj2 2333:             $curRes = $iterator->next();
1.96      bowersj2 2334:         }
                   2335:     }
1.94      bowersj2 2336: 
1.116     bowersj2 2337:     # Check: Was this only one resource, a map?
                   2338:     if ($resourceCount == 1 && $resource->is_map() && !$self->{FORCE_TOP}) { 
                   2339:         my $firstResource = $resource->map_start();
                   2340:         my $finishResource = $resource->map_finish();
                   2341:         return 
                   2342:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                   2343:                                               $finishResource, $self->{FILTER},
                   2344:                                               $self->{ALREADY_SEEN}, 
                   2345:                                               $self->{CONDITION}, 0);
                   2346:         
                   2347:     }
                   2348: 
1.98      bowersj2 2349:     # Set up some bookkeeping information.
                   2350:     $self->{CURRENT_DEPTH} = 0;
                   2351:     $self->{MAX_DEPTH} = $maxDepth;
                   2352:     $self->{STACK} = [];
                   2353:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2354: 
                   2355:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
                   2356:         push @{$self->{STACK}}, [];
                   2357:     }
                   2358: 
1.107     bowersj2 2359:     # Prime the recursion w/ the first resource **5**
1.98      bowersj2 2360:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
                   2361:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
                   2362: 
                   2363:     bless ($self);
                   2364: 
                   2365:     return $self;
                   2366: }
                   2367: 
                   2368: sub next {
                   2369:     my $self = shift;
1.162     bowersj2 2370: 
                   2371:     # If we want to return the top-level map object, and haven't yet,
                   2372:     # do so.
                   2373:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
                   2374:         $self->{HAVE_RETURNED_0} = 1;
                   2375:         return $self->{NAV_MAP}->getById('0.0');
                   2376:     }
1.98      bowersj2 2377: 
                   2378:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2379:         # grab the next from the recursive iterator 
                   2380:         my $next = $self->{RECURSIVE_ITERATOR}->next();
                   2381: 
                   2382:         # is it a begin or end map? If so, update the depth
                   2383:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
                   2384:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
                   2385: 
                   2386:         # Are we back at depth 0? If so, stop recursing
                   2387:         if ($self->{RECURSIVE_DEPTH} == 0) {
                   2388:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2389:         }
                   2390: 
                   2391:         return $next;
                   2392:     }
                   2393: 
                   2394:     if (defined($self->{FORCE_NEXT})) {
                   2395:         my $tmp = $self->{FORCE_NEXT};
                   2396:         $self->{FORCE_NEXT} = undef;
                   2397:         return $tmp;
                   2398:     }
                   2399: 
                   2400:     # Have we not yet begun? If not, return BEGIN_MAP and
                   2401:     # remember we've started.
                   2402:     if ( !$self->{STARTED} ) { 
                   2403:         $self->{STARTED} = 1;
                   2404:         return $self->BEGIN_MAP();
                   2405:     }
                   2406: 
                   2407:     # Here's the guts of the iterator.
                   2408:     
                   2409:     # Find the next resource, if any.
                   2410:     my $found = 0;
                   2411:     my $i = $self->{MAX_DEPTH};
                   2412:     my $newDepth;
                   2413:     my $here;
                   2414:     while ( $i >= 0 && !$found ) {
1.107     bowersj2 2415:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
                   2416:             $here = pop @{$self->{STACK}->[$i]}; # **7**
1.98      bowersj2 2417:             $found = 1;
                   2418:             $newDepth = $i;
                   2419:         }
                   2420:         $i--;
                   2421:     }
                   2422: 
                   2423:     # If we still didn't find anything, we're done.
                   2424:     if ( !$found ) {
                   2425:         # We need to get back down to the correct branch depth
                   2426:         if ( $self->{CURRENT_DEPTH} > 0 ) {
                   2427:             $self->{CURRENT_DEPTH}--;
                   2428:             return END_BRANCH();
                   2429:         } else {
                   2430:             return END_MAP();
                   2431:         }
                   2432:     }
                   2433: 
1.104     bowersj2 2434:     # If this is not a resource, it must be an END_BRANCH marker we want
                   2435:     # to return directly.
1.107     bowersj2 2436:     if (!ref($here)) { # **8**
1.104     bowersj2 2437:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
                   2438:             $self->{CURRENT_DEPTH}--;
                   2439:             return $here;
                   2440:         }
                   2441:     }
                   2442: 
                   2443:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
                   2444:     $self->{HERE} = $here;
                   2445: 
1.98      bowersj2 2446:     # Get to the right level
                   2447:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
                   2448:         push @{$self->{STACK}->[$newDepth]}, $here;
                   2449:         $self->{CURRENT_DEPTH}--;
                   2450:         return END_BRANCH();
                   2451:     }
                   2452:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
                   2453:         push @{$self->{STACK}->[$newDepth]}, $here;
                   2454:         $self->{CURRENT_DEPTH}++;
                   2455:         return BEGIN_BRANCH();
                   2456:     }
                   2457: 
                   2458:     # If we made it here, we have the next resource, and we're at the
                   2459:     # right branch level. So let's examine the resource for where
                   2460:     # we can get to from here.
                   2461: 
                   2462:     # So we need to look at all the resources we can get to from here,
                   2463:     # categorize them if we haven't seen them, remember if we have a new
                   2464:     my $nextUnfiltered = $here->getNext();
1.104     bowersj2 2465:     my $maxDepthAdded = -1;
                   2466:     
1.98      bowersj2 2467:     for (@$nextUnfiltered) {
                   2468:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1.104     bowersj2 2469:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
                   2470:             push @{$self->{STACK}->[$depth]}, $_;
1.98      bowersj2 2471:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
1.104     bowersj2 2472:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
1.98      bowersj2 2473:         }
                   2474:     }
1.104     bowersj2 2475: 
                   2476:     # Is this the end of a branch? If so, all of the resources examined above
                   2477:     # led to lower levels then the one we are currently at, so we push a END_BRANCH
                   2478:     # marker onto the stack so we don't forget.
                   2479:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
                   2480:     # BC branch and gets to C, it will see F as the only next resource, but it's
                   2481:     # one level lower. Thus, this is the end of the branch, since there are no
                   2482:     # more resources added to this level or above.
1.111     bowersj2 2483:     # We don't do this if the examined resource is the finish resource,
                   2484:     # because the condition given above is true, but the "END_MAP" will
                   2485:     # take care of things and we should already be at depth 0.
1.104     bowersj2 2486:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
1.111     bowersj2 2487:     if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
1.104     bowersj2 2488:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
                   2489:     }
                   2490: 
1.98      bowersj2 2491:     # That ends the main iterator logic. Now, do we want to recurse
                   2492:     # down this map (if this resource is a map)?
                   2493:     if ($self->{HERE}->is_map() &&
                   2494:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
                   2495:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
                   2496:         my $firstResource = $self->{HERE}->map_start();
                   2497:         my $finishResource = $self->{HERE}->map_finish();
                   2498: 
                   2499:         $self->{RECURSIVE_ITERATOR} = 
                   2500:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                   2501:                                               $finishResource, $self->{FILTER},
                   2502:                                               $self->{ALREADY_SEEN}, $self->{CONDITION});
                   2503:     }
                   2504: 
1.116     bowersj2 2505:     # If this is a blank resource, don't actually return it.
1.117     bowersj2 2506:     # Should you ever find you need it, make sure to add an option to the code
                   2507:     #  that you can use; other things depend on this behavior.
1.138     bowersj2 2508:     my $browsePriv = $self->{HERE}->browsePriv();
                   2509:     if (!$self->{HERE}->src() || 
                   2510:         (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
1.116     bowersj2 2511:         return $self->next();
                   2512:     }
                   2513: 
1.98      bowersj2 2514:     return $self->{HERE};
                   2515: 
                   2516: }
                   2517: 
                   2518: =pod
                   2519: 
1.174     albertel 2520: The other method available on the iterator is B<getStack>, which
                   2521: returns an array populated with the current 'stack' of maps, as
                   2522: references to the resource objects. Example: This is useful when
                   2523: making the navigation map, as we need to check whether we are under a
                   2524: page map to see if we need to link directly to the resource, or to the
                   2525: page. The first elements in the array will correspond to the top of
                   2526: the stack (most inclusive map).
1.98      bowersj2 2527: 
                   2528: =cut
                   2529: 
                   2530: sub getStack {
                   2531:     my $self=shift;
                   2532: 
                   2533:     my @stack;
                   2534: 
                   2535:     $self->populateStack(\@stack);
                   2536: 
                   2537:     return \@stack;
                   2538: }
                   2539: 
                   2540: # Private method: Calls the iterators recursively to populate the stack.
                   2541: sub populateStack {
                   2542:     my $self=shift;
                   2543:     my $stack = shift;
                   2544: 
                   2545:     push @$stack, $self->{HERE} if ($self->{HERE});
                   2546: 
                   2547:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2548:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
                   2549:     }
1.94      bowersj2 2550: }
                   2551: 
                   2552: 1;
                   2553: 
                   2554: package Apache::lonnavmaps::DFSiterator;
                   2555: 
1.100     bowersj2 2556: # Not documented in the perldoc: This is a simple iterator that just walks
                   2557: #  through the nav map and presents the resources in a depth-first search
                   2558: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
                   2559: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
                   2560: #  useful for pre-processing of some kind, and is in fact used by the main
                   2561: #  iterator that way, but that's about it.
                   2562: # One could imagine merging this into the init routine of the main iterator,
                   2563: #  but this might as well be left seperate, since it is possible some other
                   2564: #  use might be found for it. - Jeremy
1.94      bowersj2 2565: 
1.117     bowersj2 2566: # Unlike the main iterator, this DOES return all resources, even blank ones.
                   2567: #  The main iterator needs them to correctly preprocess the map.
                   2568: 
1.94      bowersj2 2569: sub BEGIN_MAP { return 1; }    # begining of a new map
                   2570: sub END_MAP { return 2; }      # end of the map
                   2571: sub FORWARD { return 1; }      # go forward
                   2572: sub BACKWARD { return 2; }
                   2573: 
1.100     bowersj2 2574: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
                   2575: #         filter hash ref (or undef), already seen hash or undef, condition
                   2576: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
1.51      bowersj2 2577: sub new {
                   2578:     # magic invocation to create a class instance
                   2579:     my $proto = shift;
                   2580:     my $class = ref($proto) || $proto;
                   2581:     my $self = {};
                   2582: 
                   2583:     $self->{NAV_MAP} = shift;
                   2584:     return undef unless ($self->{NAV_MAP});
                   2585: 
                   2586:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
                   2587:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
                   2588: 
                   2589:     # If the given resources are just the ID of the resource, get the
                   2590:     # objects
                   2591:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
                   2592:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
                   2593:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
                   2594:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
                   2595: 
                   2596:     $self->{FILTER} = shift;
                   2597: 
                   2598:     # A hash, used as a set, of resource already seen
                   2599:     $self->{ALREADY_SEEN} = shift;
1.140     bowersj2 2600:      if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1.63      bowersj2 2601:     $self->{CONDITION} = shift;
1.89      bowersj2 2602:     $self->{DIRECTION} = shift || FORWARD();
1.51      bowersj2 2603: 
1.100     bowersj2 2604:     # Flag: Have we started yet?
1.51      bowersj2 2605:     $self->{STARTED} = 0;
                   2606: 
                   2607:     # Should we continue calling the recursive iterator, if any?
                   2608:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2609:     # The recursive iterator, if any
                   2610:     $self->{RECURSIVE_ITERATOR} = undef;
                   2611:     # Are we recursing on a map, or a branch?
                   2612:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
                   2613:     # And the count of how deep it is, so that this iterator can keep track of
                   2614:     # when to pick back up again.
                   2615:     $self->{RECURSIVE_DEPTH} = 0;
                   2616: 
                   2617:     # For keeping track of our branches, we maintain our own stack
1.100     bowersj2 2618:     $self->{STACK} = [];
1.51      bowersj2 2619: 
                   2620:     # Start with the first resource
1.89      bowersj2 2621:     if ($self->{DIRECTION} == FORWARD) {
1.100     bowersj2 2622:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
1.89      bowersj2 2623:     } else {
1.100     bowersj2 2624:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
1.89      bowersj2 2625:     }
1.51      bowersj2 2626: 
                   2627:     bless($self);
                   2628:     return $self;
                   2629: }
                   2630: 
                   2631: sub next {
                   2632:     my $self = shift;
                   2633:     
                   2634:     # Are we using a recursive iterator? If so, pull from that and
                   2635:     # watch the depth; we want to resume our level at the correct time.
1.98      bowersj2 2636:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1.51      bowersj2 2637:         # grab the next from the recursive iterator
                   2638:         my $next = $self->{RECURSIVE_ITERATOR}->next();
                   2639:         
                   2640:         # is it a begin or end map? Update depth if so
                   2641:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
                   2642:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
                   2643: 
                   2644:         # Are we back at depth 0? If so, stop recursing.
                   2645:         if ($self->{RECURSIVE_DEPTH} == 0) {
                   2646:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2647:         }
                   2648:         
                   2649:         return $next;
                   2650:     }
                   2651: 
                   2652:     # Is there a current resource to grab? If not, then return
1.100     bowersj2 2653:     # END_MAP, which will end the iterator.
                   2654:     if (scalar(@{$self->{STACK}}) == 0) {
                   2655:         return $self->END_MAP();
1.51      bowersj2 2656:     }
                   2657: 
                   2658:     # Have we not yet begun? If not, return BEGIN_MAP and 
                   2659:     # remember that we've started.
                   2660:     if ( !$self->{STARTED} ) {
                   2661:         $self->{STARTED} = 1;
                   2662:         return $self->BEGIN_MAP;
                   2663:     }
                   2664: 
                   2665:     # Get the next resource in the branch
1.100     bowersj2 2666:     $self->{HERE} = pop @{$self->{STACK}};
1.52      bowersj2 2667: 
1.100     bowersj2 2668:     # remember that we've seen this, so we don't return it again later
1.51      bowersj2 2669:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
                   2670:     
                   2671:     # Get the next possible resources
1.90      bowersj2 2672:     my $nextUnfiltered;
1.89      bowersj2 2673:     if ($self->{DIRECTION} == FORWARD()) {
1.90      bowersj2 2674:         $nextUnfiltered = $self->{HERE}->getNext();
1.89      bowersj2 2675:     } else {
1.90      bowersj2 2676:         $nextUnfiltered = $self->{HERE}->getPrevious();
1.89      bowersj2 2677:     }
1.51      bowersj2 2678:     my $next = [];
                   2679: 
                   2680:     # filter the next possibilities to remove things we've 
1.100     bowersj2 2681:     # already seen.
1.51      bowersj2 2682:     foreach (@$nextUnfiltered) {
1.52      bowersj2 2683:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
                   2684:             push @$next, $_;
                   2685:         }
1.51      bowersj2 2686:     }
                   2687: 
                   2688:     while (@$next) {
1.100     bowersj2 2689:         # copy the next possibilities over to the stack
                   2690:         push @{$self->{STACK}}, shift @$next;
1.51      bowersj2 2691:     }
                   2692: 
                   2693:     # If this is a map and we want to recurse down it... (not filtered out)
1.70      bowersj2 2694:     if ($self->{HERE}->is_map() && 
1.63      bowersj2 2695:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
1.51      bowersj2 2696:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
                   2697:         my $firstResource = $self->{HERE}->map_start();
                   2698:         my $finishResource = $self->{HERE}->map_finish();
                   2699: 
                   2700:         $self->{RECURSIVE_ITERATOR} =
1.94      bowersj2 2701:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
1.63      bowersj2 2702:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
1.91      bowersj2 2703:                                              $self->{CONDITION}, $self->{DIRECTION});
1.51      bowersj2 2704:     }
                   2705: 
                   2706:     return $self->{HERE};
1.190     bowersj2 2707: }
                   2708: 
                   2709: # Identical to the full iterator methods of the same name. Hate to copy/paste
                   2710: # but I also hate to "inherit" either iterator from the other.
                   2711: 
                   2712: sub getStack {
                   2713:     my $self=shift;
                   2714: 
                   2715:     my @stack;
                   2716: 
                   2717:     $self->populateStack(\@stack);
                   2718: 
                   2719:     return \@stack;
                   2720: }
                   2721: 
                   2722: # Private method: Calls the iterators recursively to populate the stack.
                   2723: sub populateStack {
                   2724:     my $self=shift;
                   2725:     my $stack = shift;
                   2726: 
                   2727:     push @$stack, $self->{HERE} if ($self->{HERE});
                   2728: 
                   2729:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2730:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
                   2731:     }
1.51      bowersj2 2732: }
                   2733: 
1.1       www      2734: 1;
1.2       www      2735: 
1.51      bowersj2 2736: package Apache::lonnavmaps::resource;
                   2737: 
                   2738: use Apache::lonnet;
                   2739: 
                   2740: =pod
                   2741: 
                   2742: =head1 Object: resource
                   2743: 
1.174     albertel 2744: A resource object encapsulates a resource in a resource map, allowing
                   2745: easy manipulation of the resource, querying the properties of the
                   2746: resource (including user properties), and represents a reference that
                   2747: can be used as the canonical representation of the resource by
                   2748: lonnavmap clients like renderers.
                   2749: 
                   2750: A resource only makes sense in the context of a navmap, as some of the
                   2751: data is stored in the navmap object.
                   2752: 
                   2753: You will probably never need to instantiate this object directly. Use
                   2754: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
                   2755: starting resource.
1.51      bowersj2 2756: 
1.188     bowersj2 2757: Resource objects respect the parameter_hiddenparts, which suppresses 
                   2758: various parts according to the wishes of the map author. As of this
                   2759: writing, there is no way to override this parameter, and suppressed
                   2760: parts will never be returned, nor will their response types or ids be
                   2761: stored.
                   2762: 
1.51      bowersj2 2763: =head2 Public Members
                   2764: 
1.174     albertel 2765: resource objects have a hash called DATA ($resourceRef->{DATA}) that
                   2766: you can store whatever you want in. This allows you to easily do
                   2767: two-pass algorithms without worrying about managing your own
                   2768: resource->data hash.
1.51      bowersj2 2769: 
                   2770: =head2 Methods
                   2771: 
                   2772: =over 4
                   2773: 
1.174     albertel 2774: =item * B<new>($navmapRef, $idString):
                   2775: 
                   2776: The first arg is a reference to the parent navmap object. The second
                   2777: is the idString of the resource itself. Very rarely, if ever, called
                   2778: directly. Use the nav map->getByID() method.
1.70      bowersj2 2779: 
                   2780: =back
1.51      bowersj2 2781: 
                   2782: =cut
                   2783: 
                   2784: sub new {
                   2785:     # magic invocation to create a class instance
                   2786:     my $proto = shift;
                   2787:     my $class = ref($proto) || $proto;
                   2788:     my $self = {};
                   2789: 
                   2790:     $self->{NAV_MAP} = shift;
                   2791:     $self->{ID} = shift;
                   2792: 
                   2793:     # Store this new resource in the parent nav map's cache.
                   2794:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
1.66      bowersj2 2795:     $self->{RESOURCE_ERROR} = 0;
1.51      bowersj2 2796: 
                   2797:     # A hash that can be used by two-pass algorithms to store data
                   2798:     # about this resource in. Not used by the resource object
                   2799:     # directly.
                   2800:     $self->{DATA} = {};
                   2801:    
                   2802:     bless($self);
                   2803:     
                   2804:     return $self;
                   2805: }
                   2806: 
1.70      bowersj2 2807: # private function: simplify the NAV_HASH lookups we keep doing
                   2808: # pass the name, and to automatically append my ID, pass a true val on the
                   2809: # second param
                   2810: sub navHash {
                   2811:     my $self = shift;
                   2812:     my $param = shift;
                   2813:     my $id = shift;
1.115     bowersj2 2814:     return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
1.70      bowersj2 2815: }
                   2816: 
1.51      bowersj2 2817: =pod
                   2818: 
1.70      bowersj2 2819: B<Metadata Retreival>
                   2820: 
1.174     albertel 2821: These are methods that help you retrieve metadata about the resource:
                   2822: Method names are based on the fields in the compiled course
                   2823: representation.
1.70      bowersj2 2824: 
                   2825: =over 4
                   2826: 
1.174     albertel 2827: =item * B<compTitle>:
                   2828: 
                   2829: Returns a "composite title", that is equal to $res->title() if the
                   2830: resource has a title, and is otherwise the last part of the URL (e.g.,
                   2831: "problem.problem").
                   2832: 
                   2833: =item * B<ext>:
                   2834: 
                   2835: Returns true if the resource is external.
                   2836: 
                   2837: =item * B<goesto>:
                   2838: 
                   2839: Returns the "goesto" value from the compiled nav map. (It is likely
                   2840: you want to use B<getNext> instead.)
                   2841: 
                   2842: =item * B<kind>:
                   2843: 
                   2844: Returns the kind of the resource from the compiled nav map.
                   2845: 
                   2846: =item * B<randomout>:
1.106     bowersj2 2847: 
1.174     albertel 2848: Returns true if this resource was chosen to NOT be shown to the user
                   2849: by the random map selection feature. In other words, this is usually
                   2850: false.
1.70      bowersj2 2851: 
1.174     albertel 2852: =item * B<randompick>:
1.70      bowersj2 2853: 
1.174     albertel 2854: Returns true for a map if the randompick feature is being used on the
                   2855: map. (?)
1.70      bowersj2 2856: 
1.174     albertel 2857: =item * B<src>:
1.51      bowersj2 2858: 
1.174     albertel 2859: Returns the source for the resource.
1.70      bowersj2 2860: 
1.174     albertel 2861: =item * B<symb>:
1.70      bowersj2 2862: 
1.174     albertel 2863: Returns the symb for the resource.
1.70      bowersj2 2864: 
1.174     albertel 2865: =item * B<title>:
1.70      bowersj2 2866: 
1.174     albertel 2867: Returns the title of the resource.
                   2868: 
                   2869: =item * B<to>:
                   2870: 
                   2871: Returns the "to" value from the compiled nav map. (It is likely you
                   2872: want to use B<getNext> instead.)
1.51      bowersj2 2873: 
                   2874: =back
                   2875: 
                   2876: =cut
                   2877: 
                   2878: # These info functions can be used directly, as they don't return
                   2879: # resource information.
1.85      bowersj2 2880: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
1.70      bowersj2 2881: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
1.85      bowersj2 2882: sub from { my $self=shift; return $self->navHash("from_", 1); }
1.51      bowersj2 2883: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
                   2884: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
1.68      bowersj2 2885: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
                   2886: sub randompick { 
                   2887:     my $self = shift;
                   2888:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
                   2889:                                                '.0.parameter_randompick'};
                   2890: }
1.51      bowersj2 2891: sub src { 
                   2892:     my $self=shift;
                   2893:     return $self->navHash("src_", 1);
                   2894: }
                   2895: sub symb {
                   2896:     my $self=shift;
                   2897:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
                   2898:     my $symbSrc = &Apache::lonnet::declutter($self->src());
                   2899:     return &Apache::lonnet::declutter(
                   2900:          $self->navHash('map_id_'.$first)) 
                   2901:         . '___' . $second . '___' . $symbSrc;
                   2902: }
1.70      bowersj2 2903: sub title { my $self=shift; return $self->navHash("title_", 1); }
                   2904: sub to { my $self=shift; return $self->navHash("to_", 1); }
1.106     bowersj2 2905: sub compTitle {
                   2906:     my $self = shift;
                   2907:     my $title = $self->title();
1.176     www      2908:     $title=~s/\&colon\;/\:/gs;
1.106     bowersj2 2909:     if (!$title) {
                   2910:         $title = $self->src();
                   2911:         $title = substr($title, rindex($title, '/') + 1);
                   2912:     }
                   2913:     return $title;
                   2914: }
1.70      bowersj2 2915: =pod
                   2916: 
                   2917: B<Predicate Testing the Resource>
                   2918: 
                   2919: These methods are shortcuts to deciding if a given resource has a given property.
                   2920: 
                   2921: =over 4
                   2922: 
1.174     albertel 2923: =item * B<is_map>:
                   2924: 
                   2925: Returns true if the resource is a map type.
                   2926: 
                   2927: =item * B<is_problem>:
1.70      bowersj2 2928: 
1.174     albertel 2929: Returns true if the resource is a problem type, false
                   2930: otherwise. (Looks at the extension on the src field; might need more
                   2931: to work correctly.)
1.70      bowersj2 2932: 
1.174     albertel 2933: =item * B<is_page>:
1.70      bowersj2 2934: 
1.174     albertel 2935: Returns true if the resource is a page.
                   2936: 
                   2937: =item * B<is_sequence>:
                   2938: 
                   2939: Returns true if the resource is a sequence.
1.70      bowersj2 2940: 
                   2941: =back
                   2942: 
                   2943: =cut
                   2944: 
                   2945: 
                   2946: sub is_html {
1.51      bowersj2 2947:     my $self=shift;
                   2948:     my $src = $self->src();
1.70      bowersj2 2949:     return ($src =~ /html$/);
1.51      bowersj2 2950: }
1.70      bowersj2 2951: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
                   2952: sub is_page {
1.51      bowersj2 2953:     my $self=shift;
                   2954:     my $src = $self->src();
1.205   ! bowersj2 2955:     return $self->navHash("is_map_", 1) && 
        !          2956: 	$self->navHash("map_type_" . $self->map_pc()) eq 'page';
1.51      bowersj2 2957: }
1.70      bowersj2 2958: sub is_problem {
1.51      bowersj2 2959:     my $self=shift;
                   2960:     my $src = $self->src();
1.70      bowersj2 2961:     return ($src =~ /problem$/);
1.51      bowersj2 2962: }
1.70      bowersj2 2963: sub is_sequence {
1.51      bowersj2 2964:     my $self=shift;
                   2965:     my $src = $self->src();
1.205   ! bowersj2 2966:     return $self->navHash("is_map_", 1) && 
        !          2967: 	$self->navHash("map_type_" . $self->map_pc()) eq 'sequence';
1.51      bowersj2 2968: }
                   2969: 
1.101     bowersj2 2970: # Private method: Shells out to the parmval in the nav map, handler parts.
1.51      bowersj2 2971: sub parmval {
                   2972:     my $self = shift;
                   2973:     my $what = shift;
1.185     bowersj2 2974:     my $part = shift;
                   2975:     if (!defined($part)) { 
                   2976:         $part = '0'; 
                   2977:     }
1.51      bowersj2 2978:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
                   2979: }
                   2980: 
1.70      bowersj2 2981: =pod
                   2982: 
                   2983: B<Map Methods>
                   2984: 
1.174     albertel 2985: These methods are useful for getting information about the map
                   2986: properties of the resource, if the resource is a map (B<is_map>).
1.70      bowersj2 2987: 
                   2988: =over 4
                   2989: 
1.174     albertel 2990: =item * B<map_finish>:
                   2991: 
                   2992: Returns a reference to a resource object corresponding to the finish
                   2993: resource of the map.
1.70      bowersj2 2994: 
1.174     albertel 2995: =item * B<map_pc>:
1.70      bowersj2 2996: 
1.174     albertel 2997: Returns the pc value of the map, which is the first number that
                   2998: appears in the resource ID of the resources in the map, and is the
                   2999: number that appears around the middle of the symbs of the resources in
                   3000: that map.
1.70      bowersj2 3001: 
1.174     albertel 3002: =item * B<map_start>:
                   3003: 
                   3004: Returns a reference to a resource object corresponding to the start
                   3005: resource of the map.
                   3006: 
                   3007: =item * B<map_type>:
                   3008: 
                   3009: Returns a string with the type of the map in it.
1.70      bowersj2 3010: 
                   3011: =back
1.51      bowersj2 3012: 
1.70      bowersj2 3013: =cut
1.51      bowersj2 3014: 
                   3015: sub map_finish {
                   3016:     my $self = shift;
                   3017:     my $src = $self->src();
1.144     bowersj2 3018:     $src = Apache::lonnet::clutter($src);
1.51      bowersj2 3019:     my $res = $self->navHash("map_finish_$src", 0);
                   3020:     $res = $self->{NAV_MAP}->getById($res);
                   3021:     return $res;
                   3022: }
1.70      bowersj2 3023: sub map_pc {
                   3024:     my $self = shift;
                   3025:     my $src = $self->src();
                   3026:     return $self->navHash("map_pc_$src", 0);
                   3027: }
1.51      bowersj2 3028: sub map_start {
                   3029:     my $self = shift;
                   3030:     my $src = $self->src();
1.144     bowersj2 3031:     $src = Apache::lonnet::clutter($src);
1.51      bowersj2 3032:     my $res = $self->navHash("map_start_$src", 0);
                   3033:     $res = $self->{NAV_MAP}->getById($res);
                   3034:     return $res;
                   3035: }
                   3036: sub map_type {
                   3037:     my $self = shift;
                   3038:     my $pc = $self->map_pc();
                   3039:     return $self->navHash("map_type_$pc", 0);
                   3040: }
                   3041: 
                   3042: #####
                   3043: # Property queries
                   3044: #####
                   3045: 
                   3046: # These functions will be responsible for returning the CORRECT
                   3047: # VALUE for the parameter, no matter what. So while they may look
                   3048: # like direct calls to parmval, they can be more then that.
                   3049: # So, for instance, the duedate function should use the "duedatetype"
                   3050: # information, rather then the resource object user.
                   3051: 
                   3052: =pod
                   3053: 
                   3054: =head2 Resource Parameters
                   3055: 
1.174     albertel 3056: In order to use the resource parameters correctly, the nav map must
                   3057: have been instantiated with genCourseAndUserOptions set to true, so
                   3058: the courseopt and useropt is read correctly. Then, you can call these
                   3059: functions to get the relevant parameters for the resource. Each
                   3060: function defaults to part "0", but can be directed to another part by
                   3061: passing the part as the parameter.
                   3062: 
                   3063: These methods are responsible for getting the parameter correct, not
                   3064: merely reflecting the contents of the GDBM hashes. As we move towards
                   3065: dates relative to other dates, these methods should be updated to
                   3066: reflect that. (Then, anybody using these methods will not have to update
                   3067: their code.)
                   3068: 
                   3069: =over 4
                   3070: 
                   3071: =item * B<acc>:
                   3072: 
                   3073: Get the Client IP/Name Access Control information.
1.51      bowersj2 3074: 
1.174     albertel 3075: =item * B<answerdate>:
1.51      bowersj2 3076: 
1.174     albertel 3077: Get the answer-reveal date for the problem.
                   3078: 
                   3079: =item * B<duedate>:
                   3080: 
                   3081: Get the due date for the problem.
                   3082: 
                   3083: =item * B<tries>:
                   3084: 
                   3085: Get the number of tries the student has used on the problem.
                   3086: 
                   3087: =item * B<maxtries>:
                   3088: 
                   3089: Get the number of max tries allowed.
                   3090: 
                   3091: =item * B<opendate>:
1.51      bowersj2 3092: 
1.174     albertel 3093: Get the open date for the problem.
1.51      bowersj2 3094: 
1.174     albertel 3095: =item * B<sig>:
1.51      bowersj2 3096: 
1.174     albertel 3097: Get the significant figures setting.
1.51      bowersj2 3098: 
1.174     albertel 3099: =item * B<tol>:
1.51      bowersj2 3100: 
1.174     albertel 3101: Get the tolerance for the problem.
1.51      bowersj2 3102: 
1.174     albertel 3103: =item * B<tries>:
1.51      bowersj2 3104: 
1.174     albertel 3105: Get the number of tries the user has already used on the problem.
1.51      bowersj2 3106: 
1.174     albertel 3107: =item * B<type>:
1.51      bowersj2 3108: 
1.174     albertel 3109: Get the question type for the problem.
1.70      bowersj2 3110: 
1.174     albertel 3111: =item * B<weight>:
1.51      bowersj2 3112: 
1.174     albertel 3113: Get the weight for the problem.
1.51      bowersj2 3114: 
                   3115: =back
                   3116: 
                   3117: =cut
                   3118: 
                   3119: sub acc {
                   3120:     (my $self, my $part) = @_;
                   3121:     return $self->parmval("acc", $part);
                   3122: }
                   3123: sub answerdate {
                   3124:     (my $self, my $part) = @_;
                   3125:     # Handle intervals
                   3126:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
                   3127:         return $self->duedate($part) + 
                   3128:             $self->parmval("answerdate", $part);
                   3129:     }
                   3130:     return $self->parmval("answerdate", $part);
1.106     bowersj2 3131: }
1.108     bowersj2 3132: sub awarded { my $self = shift; return $self->queryRestoreHash('awarded', shift); }
1.51      bowersj2 3133: sub duedate {
                   3134:     (my $self, my $part) = @_;
                   3135:     return $self->parmval("duedate", $part);
                   3136: }
                   3137: sub maxtries {
                   3138:     (my $self, my $part) = @_;
                   3139:     return $self->parmval("maxtries", $part);
                   3140: }
                   3141: sub opendate {
                   3142:     (my $self, my $part) = @_;
                   3143:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
                   3144:         return $self->duedate($part) -
                   3145:             $self->parmval("opendate", $part);
                   3146:     }
                   3147:     return $self->parmval("opendate");
                   3148: }
1.185     bowersj2 3149: sub problemstatus {
                   3150:     (my $self, my $part) = @_;
                   3151:     return $self->parmval("problemstatus", $part);
                   3152: }
1.51      bowersj2 3153: sub sig {
                   3154:     (my $self, my $part) = @_;
                   3155:     return $self->parmval("sig", $part);
                   3156: }
                   3157: sub tol {
                   3158:     (my $self, my $part) = @_;
                   3159:     return $self->parmval("tol", $part);
                   3160: }
1.108     bowersj2 3161: sub tries { 
                   3162:     my $self = shift; 
                   3163:     my $tries = $self->queryRestoreHash('tries', shift);
                   3164:     if (!defined($tries)) { return '0';}
1.51      bowersj2 3165:     return $tries;
                   3166: }
1.70      bowersj2 3167: sub type {
                   3168:     (my $self, my $part) = @_;
                   3169:     return $self->parmval("type", $part);
                   3170: }
1.109     bowersj2 3171: sub weight { 
                   3172:     my $self = shift; my $part = shift;
1.70      bowersj2 3173:     return $self->parmval("weight", $part);
                   3174: }
1.51      bowersj2 3175: 
                   3176: # Multiple things need this
                   3177: sub getReturnHash {
                   3178:     my $self = shift;
                   3179:     
                   3180:     if (!defined($self->{RETURN_HASH})) {
1.84      bowersj2 3181:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
1.51      bowersj2 3182:         $self->{RETURN_HASH} = \%tmpHash;
                   3183:     }
                   3184: }       
                   3185: 
                   3186: ######
                   3187: # Status queries
                   3188: ######
                   3189: 
                   3190: # These methods query the status of problems.
                   3191: 
                   3192: # If we need to count parts, this function determines the number of
                   3193: # parts from the metadata. When called, it returns a reference to a list
                   3194: # of strings corresponding to the parts. (Thus, using it in a scalar context
                   3195: # tells you how many parts you have in the problem:
                   3196: # $partcount = scalar($resource->countParts());
                   3197: # Don't use $self->{PARTS} directly because you don't know if it's been
                   3198: # computed yet.
                   3199: 
                   3200: =pod
                   3201: 
                   3202: =head2 Resource misc
                   3203: 
                   3204: Misc. functions for the resource.
                   3205: 
                   3206: =over 4
                   3207: 
1.174     albertel 3208: =item * B<hasDiscussion>:
1.59      bowersj2 3209: 
1.174     albertel 3210: Returns a false value if there has been discussion since the user last
                   3211: logged in, true if there has. Always returns false if the discussion
                   3212: data was not extracted when the nav map was constructed.
                   3213: 
                   3214: =item * B<getFeedback>:
                   3215: 
                   3216: Gets the feedback for the resource and returns the raw feedback string
                   3217: for the resource, or the null string if there is no feedback or the
                   3218: email data was not extracted when the nav map was constructed. Usually
                   3219: used like this:
1.59      bowersj2 3220: 
                   3221:  for (split(/\,/, $res->getFeedback())) {
                   3222:     my $link = &Apache::lonnet::escape($_);
                   3223:     ...
                   3224: 
                   3225: and use the link as appropriate.
                   3226: 
                   3227: =cut
                   3228: 
                   3229: sub hasDiscussion {
                   3230:     my $self = shift;
                   3231:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
                   3232: }
                   3233: 
                   3234: sub getFeedback {
                   3235:     my $self = shift;
1.124     bowersj2 3236:     my $source = $self->src();
1.125     bowersj2 3237:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
1.124     bowersj2 3238:     return $self->{NAV_MAP}->getFeedback($source);
                   3239: }
                   3240: 
                   3241: sub getErrors {
                   3242:     my $self = shift;
                   3243:     my $source = $self->src();
                   3244:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
                   3245:     return $self->{NAV_MAP}->getErrors($source);
1.59      bowersj2 3246: }
                   3247: 
                   3248: =pod
                   3249: 
1.174     albertel 3250: =item * B<parts>():
1.51      bowersj2 3251: 
1.174     albertel 3252: Returns a list reference containing sorted strings corresponding to
1.193     bowersj2 3253: each part of the problem. Single part problems have only a part '0'.
                   3254: Multipart problems do not return their part '0', since they typically
                   3255: do not really matter. 
1.174     albertel 3256: 
                   3257: =item * B<countParts>():
                   3258: 
                   3259: Returns the number of parts of the problem a student can answer. Thus,
                   3260: for single part problems, returns 1. For multipart, it returns the
1.193     bowersj2 3261: number of parts in the problem, not including psuedo-part 0. 
1.51      bowersj2 3262: 
1.192     bowersj2 3263: =item * B<multipart>():
                   3264: 
1.193     bowersj2 3265: Returns true if the problem is multipart, false otherwise. Use this instead
                   3266: of countParts if all you want is multipart/not multipart.
1.192     bowersj2 3267: 
1.187     bowersj2 3268: =item * B<responseType>($part):
                   3269: 
                   3270: Returns the response type of the part, without the word "response" on the
                   3271: end. Example return values: 'string', 'essay', 'numeric', etc.
                   3272: 
1.193     bowersj2 3273: =item * B<responseIds>($part):
1.187     bowersj2 3274: 
1.193     bowersj2 3275: Retreives the response IDs for the given part as an array reference containing
                   3276: strings naming the response IDs. This may be empty.
1.187     bowersj2 3277: 
1.51      bowersj2 3278: =back
                   3279: 
                   3280: =cut
                   3281: 
                   3282: sub parts {
                   3283:     my $self = shift;
                   3284: 
1.192     bowersj2 3285:     if ($self->ext) { return []; }
1.67      bowersj2 3286: 
1.51      bowersj2 3287:     $self->extractParts();
                   3288:     return $self->{PARTS};
                   3289: }
                   3290: 
                   3291: sub countParts {
                   3292:     my $self = shift;
                   3293:     
                   3294:     my $parts = $self->parts();
1.191     bowersj2 3295: 
                   3296:     # If I left this here, then it's not necessary.
                   3297:     #my $delta = 0;
                   3298:     #for my $part (@$parts) {
                   3299:     #    if ($part eq '0') { $delta--; }
                   3300:     #}
1.66      bowersj2 3301: 
                   3302:     if ($self->{RESOURCE_ERROR}) {
                   3303:         return 0;
                   3304:     }
                   3305: 
1.191     bowersj2 3306:     return scalar(@{$parts}); # + $delta;
1.192     bowersj2 3307: }
                   3308: 
                   3309: sub multipart {
                   3310:     my $self = shift;
                   3311:     return $self->countParts() > 1;
1.51      bowersj2 3312: }
                   3313: 
1.187     bowersj2 3314: sub responseType {
1.184     bowersj2 3315:     my $self = shift;
                   3316:     my $part = shift;
                   3317: 
                   3318:     $self->extractParts();
1.187     bowersj2 3319:     return $self->{RESPONSE_TYPE}->{$part};
                   3320: }
                   3321: 
1.193     bowersj2 3322: sub responseIds {
1.187     bowersj2 3323:     my $self = shift;
                   3324:     my $part = shift;
                   3325: 
                   3326:     $self->extractParts();
                   3327:     return $self->{RESPONSE_IDS}->{$part};
1.184     bowersj2 3328: }
                   3329: 
                   3330: # Private function: Extracts the parts information, both part names and
1.187     bowersj2 3331: # part types, and saves it. 
1.51      bowersj2 3332: sub extractParts { 
                   3333:     my $self = shift;
                   3334:     
1.153     bowersj2 3335:     return if (defined($self->{PARTS}));
1.67      bowersj2 3336:     return if ($self->ext);
1.51      bowersj2 3337: 
                   3338:     $self->{PARTS} = [];
                   3339: 
1.181     bowersj2 3340:     my %parts;
                   3341: 
1.82      bowersj2 3342:     # Retrieve part count, if this is a problem
                   3343:     if ($self->is_problem()) {
1.152     matthew  3344:         my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
1.82      bowersj2 3345:         if (!$metadata) {
                   3346:             $self->{RESOURCE_ERROR} = 1;
                   3347:             $self->{PARTS} = [];
1.184     bowersj2 3348:             $self->{PART_TYPE} = {};
1.82      bowersj2 3349:             return;
                   3350:         }
                   3351:         foreach (split(/\,/,$metadata)) {
1.152     matthew  3352:             if ($_ =~ /^part_(.*)$/) {
1.147     bowersj2 3353:                 my $part = $1;
1.183     bowersj2 3354:                 # This floods the logs if it blows up
                   3355:                 if (defined($parts{$part})) {
                   3356:                     Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->symb());
                   3357:                   }
1.181     bowersj2 3358: 
1.147     bowersj2 3359:                 # check to see if part is turned off.
1.181     bowersj2 3360: 
                   3361:                 if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
                   3362:                     $parts{$part} = 1;
1.147     bowersj2 3363:                 }
1.82      bowersj2 3364:             }
1.51      bowersj2 3365:         }
1.82      bowersj2 3366:         
                   3367:         
1.181     bowersj2 3368:         my @sortedParts = sort keys %parts;
1.82      bowersj2 3369:         $self->{PARTS} = \@sortedParts;
1.187     bowersj2 3370: 
                   3371:         my %responseIdHash;
                   3372:         my %responseTypeHash;
                   3373: 
1.189     bowersj2 3374: 
                   3375:         # Init the responseIdHash
                   3376:         foreach (@{$self->{PARTS}}) {
                   3377:             $responseIdHash{$_} = [];
                   3378:         }
                   3379: 
1.187     bowersj2 3380:         # Now, the unfortunate thing about this is that parts, part name, and
                   3381:         # response if are delimited by underscores, but both the part
                   3382:         # name and response id can themselves have underscores in them.
                   3383:         # So we have to use our knowlege of part names to figure out 
                   3384:         # where the part names begin and end, and even then, it is possible
                   3385:         # to construct ambiguous situations.
                   3386:         foreach (split /,/, $metadata) {
                   3387:             if ($_ =~ /^([a-zA-Z]+)response_(.*)/) {
                   3388:                 my $responseType = $1;
                   3389:                 my $partStuff = $2;
                   3390:                 my $partIdSoFar = '';
                   3391:                 my @partChunks = split /_/, $partStuff;
                   3392:                 my $i = 0;
                   3393: 
                   3394:                 for ($i = 0; $i < scalar(@partChunks); $i++) {
                   3395:                     if ($partIdSoFar) { $partIdSoFar .= '_'; }
                   3396:                     $partIdSoFar .= $partChunks[$i];
                   3397:                     if ($parts{$partIdSoFar}) {
                   3398:                         my @otherChunks = @partChunks[$i+1..$#partChunks];
                   3399:                         my $responseId = join('_', @otherChunks);
1.188     bowersj2 3400:                         push @{$responseIdHash{$partIdSoFar}}, $responseId;
1.187     bowersj2 3401:                         $responseTypeHash{$partIdSoFar} = $responseType;
                   3402:                         last;
                   3403:                     }
                   3404:                 }
                   3405:             }
                   3406:         }
                   3407: 
                   3408:         $self->{RESPONSE_IDS} = \%responseIdHash;
                   3409:         $self->{RESPONSE_TYPES} = \%responseTypeHash;
1.154     bowersj2 3410:     }
                   3411: 
1.51      bowersj2 3412:     return;
                   3413: }
                   3414: 
                   3415: =pod
                   3416: 
                   3417: =head2 Resource Status
                   3418: 
1.174     albertel 3419: Problem resources have status information, reflecting their various
                   3420: dates and completion statuses.
1.51      bowersj2 3421: 
1.174     albertel 3422: There are two aspects to the status: the date-related information and
                   3423: the completion information.
1.51      bowersj2 3424: 
1.174     albertel 3425: Idiomatic usage of these two methods would probably look something
                   3426: like
1.51      bowersj2 3427: 
                   3428:  foreach ($resource->parts()) {
                   3429:     my $dateStatus = $resource->getDateStatus($_);
                   3430:     my $completionStatus = $resource->getCompletionStatus($_);
                   3431: 
1.70      bowersj2 3432:     or
                   3433: 
                   3434:     my $status = $resource->status($_);
                   3435: 
1.51      bowersj2 3436:     ... use it here ...
                   3437:  }
                   3438: 
1.174     albertel 3439: Which you use depends on exactly what you are looking for. The
                   3440: status() function has been optimized for the nav maps display and may
                   3441: not precisely match what you need elsewhere.
1.101     bowersj2 3442: 
1.174     albertel 3443: The symbolic constants shown below can be accessed through the
                   3444: resource object: C<$res->OPEN>.
1.101     bowersj2 3445: 
1.51      bowersj2 3446: =over 4
                   3447: 
1.174     albertel 3448: =item * B<getDateStatus>($part):
                   3449: 
                   3450: ($part defaults to 0). A convenience function that returns a symbolic
                   3451: constant telling you about the date status of the part. The possible
                   3452: return values are:
1.51      bowersj2 3453: 
                   3454: =back
                   3455: 
                   3456: B<Date Codes>
                   3457: 
                   3458: =over 4
                   3459: 
1.174     albertel 3460: =item * B<OPEN_LATER>:
                   3461: 
                   3462: The problem will be opened later.
                   3463: 
                   3464: =item * B<OPEN>:
                   3465: 
                   3466: Open and not yet due.
                   3467: 
1.51      bowersj2 3468: 
1.174     albertel 3469: =item * B<PAST_DUE_ANSWER_LATER>:
1.51      bowersj2 3470: 
1.174     albertel 3471: The due date has passed, but the answer date has not yet arrived.
1.59      bowersj2 3472: 
1.174     albertel 3473: =item * B<PAST_DUE_NO_ANSWER>:
1.54      bowersj2 3474: 
1.174     albertel 3475: The due date has passed and there is no answer opening date set.
1.51      bowersj2 3476: 
1.174     albertel 3477: =item * B<ANSWER_OPEN>:
1.51      bowersj2 3478: 
1.174     albertel 3479: The answer date is here.
                   3480: 
                   3481: =item * B<NETWORK_FAILURE>:
                   3482: 
                   3483: The information is unknown due to network failure.
1.51      bowersj2 3484: 
                   3485: =back
                   3486: 
                   3487: =cut
                   3488: 
                   3489: # Apparently the compiler optimizes these into constants automatically
1.54      bowersj2 3490: sub OPEN_LATER             { return 0; }
                   3491: sub OPEN                   { return 1; }
                   3492: sub PAST_DUE_NO_ANSWER     { return 2; }
                   3493: sub PAST_DUE_ANSWER_LATER  { return 3; }
                   3494: sub ANSWER_OPEN            { return 4; }
                   3495: sub NOTHING_SET            { return 5; } 
                   3496: sub NETWORK_FAILURE        { return 100; }
                   3497: 
                   3498: # getDateStatus gets the date status for a given problem part. 
                   3499: # Because answer date, due date, and open date are fully independent
                   3500: # (i.e., it is perfectly possible to *only* have an answer date), 
                   3501: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
                   3502: # (past, future, none given). This function handles this with a decision
                   3503: # tree. Read the comments to follow the decision tree.
1.51      bowersj2 3504: 
                   3505: sub getDateStatus {
                   3506:     my $self = shift;
                   3507:     my $part = shift;
                   3508:     $part = "0" if (!defined($part));
1.54      bowersj2 3509: 
                   3510:     # Always return network failure if there was one.
1.51      bowersj2 3511:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3512: 
                   3513:     my $now = time();
                   3514: 
1.53      bowersj2 3515:     my $open = $self->opendate($part);
                   3516:     my $due = $self->duedate($part);
                   3517:     my $answer = $self->answerdate($part);
                   3518: 
                   3519:     if (!$open && !$due && !$answer) {
                   3520:         # no data on the problem at all
                   3521:         # should this be the same as "open later"? think multipart.
                   3522:         return $self->NOTHING_SET;
                   3523:     }
1.59      bowersj2 3524:     if (!$open || $now < $open) {return $self->OPEN_LATER}
                   3525:     if (!$due || $now < $due) {return $self->OPEN}
                   3526:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
                   3527:     if ($answer) { return $self->ANSWER_OPEN; }
1.54      bowersj2 3528:     return PAST_DUE_NO_ANSWER;
1.51      bowersj2 3529: }
                   3530: 
                   3531: =pod
                   3532: 
                   3533: B<>
                   3534: 
                   3535: =over 4
                   3536: 
1.174     albertel 3537: =item * B<getCompletionStatus>($part):
1.51      bowersj2 3538: 
1.174     albertel 3539: ($part defaults to 0.) A convenience function that returns a symbolic
                   3540: constant telling you about the completion status of the part, with the
                   3541: following possible results:
                   3542: 
                   3543: =back
1.51      bowersj2 3544: 
                   3545: B<Completion Codes>
                   3546: 
                   3547: =over 4
                   3548: 
1.174     albertel 3549: =item * B<NOT_ATTEMPTED>:
                   3550: 
                   3551: Has not been attempted at all.
                   3552: 
                   3553: =item * B<INCORRECT>:
                   3554: 
                   3555: Attempted, but wrong by student.
1.51      bowersj2 3556: 
1.174     albertel 3557: =item * B<INCORRECT_BY_OVERRIDE>:
1.51      bowersj2 3558: 
1.174     albertel 3559: Attempted, but wrong by instructor override.
1.51      bowersj2 3560: 
1.174     albertel 3561: =item * B<CORRECT>:
1.51      bowersj2 3562: 
1.174     albertel 3563: Correct or correct by instructor.
1.51      bowersj2 3564: 
1.174     albertel 3565: =item * B<CORRECT_BY_OVERRIDE>:
1.51      bowersj2 3566: 
1.174     albertel 3567: Correct by instructor override.
1.51      bowersj2 3568: 
1.174     albertel 3569: =item * B<EXCUSED>:
                   3570: 
                   3571: Excused. Not yet implemented.
                   3572: 
                   3573: =item * B<NETWORK_FAILURE>:
                   3574: 
                   3575: Information not available due to network failure.
                   3576: 
                   3577: =item * B<ATTEMPTED>:
                   3578: 
                   3579: Attempted, and not yet graded.
1.69      bowersj2 3580: 
1.51      bowersj2 3581: =back
                   3582: 
                   3583: =cut
                   3584: 
1.53      bowersj2 3585: sub NOT_ATTEMPTED         { return 10; }
                   3586: sub INCORRECT             { return 11; }
                   3587: sub INCORRECT_BY_OVERRIDE { return 12; }
                   3588: sub CORRECT               { return 13; }
                   3589: sub CORRECT_BY_OVERRIDE   { return 14; }
                   3590: sub EXCUSED               { return 15; }
1.69      bowersj2 3591: sub ATTEMPTED             { return 16; }
1.51      bowersj2 3592: 
                   3593: sub getCompletionStatus {
                   3594:     my $self = shift;
                   3595:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3596: 
1.108     bowersj2 3597:     my $status = $self->queryRestoreHash('solved', shift);
1.51      bowersj2 3598: 
                   3599:     # Left as seperate if statements in case we ever do more with this
                   3600:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
                   3601:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
                   3602:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
                   3603:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
                   3604:     if ($status eq 'excused') {return $self->EXCUSED; }
1.69      bowersj2 3605:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
1.51      bowersj2 3606:     return $self->NOT_ATTEMPTED;
1.108     bowersj2 3607: }
                   3608: 
                   3609: sub queryRestoreHash {
                   3610:     my $self = shift;
                   3611:     my $hashentry = shift;
                   3612:     my $part = shift;
1.185     bowersj2 3613:     $part = "0" if (!defined($part) || $part eq '');
1.108     bowersj2 3614:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3615: 
                   3616:     $self->getReturnHash();
                   3617: 
                   3618:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
1.51      bowersj2 3619: }
                   3620: 
                   3621: =pod
                   3622: 
                   3623: B<Composite Status>
                   3624: 
1.174     albertel 3625: Along with directly returning the date or completion status, the
                   3626: resource object includes a convenience function B<status>() that will
                   3627: combine the two status tidbits into one composite status that can
1.191     bowersj2 3628: represent the status of the resource as a whole. This method represents
                   3629: the concept of the thing we want to display to the user on the nav maps
                   3630: screen, which is a combination of completion and open status. The precise logic is
1.174     albertel 3631: documented in the comments of the status method. The following results
                   3632: may be returned, all available as methods on the resource object
1.185     bowersj2 3633: ($res->NETWORK_FAILURE): In addition to the return values that match
                   3634: the date or completion status, this function can return "ANSWER_SUBMITTED"
                   3635: if that problemstatus parameter value is set to No, suppressing the
                   3636: incorrect/correct feedback.
1.51      bowersj2 3637: 
                   3638: =over 4
                   3639: 
1.174     albertel 3640: =item * B<NETWORK_FAILURE>:
                   3641: 
                   3642: The network has failed and the information is not available.
1.51      bowersj2 3643: 
1.174     albertel 3644: =item * B<NOTHING_SET>:
1.53      bowersj2 3645: 
1.174     albertel 3646: No dates have been set for this problem (part) at all. (Because only
                   3647: certain parts of a multi-part problem may be assigned, this can not be
                   3648: collapsed into "open later", as we do not know a given part will EVER
                   3649: be opened. For single part, this is the same as "OPEN_LATER".)
1.51      bowersj2 3650: 
1.174     albertel 3651: =item * B<CORRECT>:
1.51      bowersj2 3652: 
1.174     albertel 3653: For any reason at all, the part is considered correct.
1.54      bowersj2 3654: 
1.174     albertel 3655: =item * B<EXCUSED>:
1.51      bowersj2 3656: 
1.174     albertel 3657: For any reason at all, the problem is excused.
1.51      bowersj2 3658: 
1.174     albertel 3659: =item * B<PAST_DUE_NO_ANSWER>:
1.51      bowersj2 3660: 
1.174     albertel 3661: The problem is past due, not considered correct, and no answer date is
                   3662: set.
1.51      bowersj2 3663: 
1.174     albertel 3664: =item * B<PAST_DUE_ANSWER_LATER>:
1.51      bowersj2 3665: 
1.174     albertel 3666: The problem is past due, not considered correct, and an answer date in
                   3667: the future is set.
1.51      bowersj2 3668: 
1.174     albertel 3669: =item * B<ANSWER_OPEN>:
                   3670: 
                   3671: The problem is past due, not correct, and the answer is now available.
                   3672: 
                   3673: =item * B<OPEN_LATER>:
                   3674: 
                   3675: The problem is not yet open.
                   3676: 
                   3677: =item * B<TRIES_LEFT>:
                   3678: 
                   3679: The problem is open, has been tried, is not correct, but there are
                   3680: tries left.
                   3681: 
                   3682: =item * B<INCORRECT>:
                   3683: 
                   3684: The problem is open, and all tries have been used without getting the
                   3685: correct answer.
                   3686: 
                   3687: =item * B<OPEN>:
                   3688: 
                   3689: The item is open and not yet tried.
                   3690: 
                   3691: =item * B<ATTEMPTED>:
                   3692: 
                   3693: The problem has been attempted.
1.69      bowersj2 3694: 
1.185     bowersj2 3695: =item * B<ANSWER_SUBMITTED>:
                   3696: 
                   3697: An answer has been submitted, but the student should not see it.
                   3698: 
1.51      bowersj2 3699: =back
                   3700: 
                   3701: =cut
                   3702: 
1.185     bowersj2 3703: sub TRIES_LEFT       { return 20; }
                   3704: sub ANSWER_SUBMITTED { return 21; }
1.51      bowersj2 3705: 
                   3706: sub status {
                   3707:     my $self = shift;
                   3708:     my $part = shift;
                   3709:     if (!defined($part)) { $part = "0"; }
                   3710:     my $completionStatus = $self->getCompletionStatus($part);
                   3711:     my $dateStatus = $self->getDateStatus($part);
                   3712: 
                   3713:     # What we have is a two-dimensional matrix with 4 entries on one
                   3714:     # dimension and 5 entries on the other, which we want to colorize,
1.54      bowersj2 3715:     # plus network failure and "no date data at all".
1.51      bowersj2 3716: 
1.53      bowersj2 3717:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
1.51      bowersj2 3718: 
1.186     bowersj2 3719:     my $suppressFeedback = lc($self->parmval("problemstatus", $part)) eq 'no';
1.185     bowersj2 3720: 
1.51      bowersj2 3721:     # There are a few whole rows we can dispose of:
1.53      bowersj2 3722:     if ($completionStatus == CORRECT ||
                   3723:         $completionStatus == CORRECT_BY_OVERRIDE ) {
1.185     bowersj2 3724:         return $suppressFeedback? ANSWER_SUBMITTED : CORRECT; 
1.69      bowersj2 3725:     }
                   3726: 
                   3727:     if ($completionStatus == ATTEMPTED) {
                   3728:         return ATTEMPTED;
1.53      bowersj2 3729:     }
                   3730: 
                   3731:     # If it's EXCUSED, then return that no matter what
                   3732:     if ($completionStatus == EXCUSED) {
                   3733:         return EXCUSED; 
1.51      bowersj2 3734:     }
                   3735: 
1.53      bowersj2 3736:     if ($dateStatus == NOTHING_SET) {
                   3737:         return NOTHING_SET;
1.51      bowersj2 3738:     }
                   3739: 
1.69      bowersj2 3740:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
                   3741:     # by 4 matrix (date statuses).
1.51      bowersj2 3742: 
1.54      bowersj2 3743:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
1.59      bowersj2 3744:         $dateStatus == PAST_DUE_NO_ANSWER ) {
1.54      bowersj2 3745:         return $dateStatus; 
1.51      bowersj2 3746:     }
                   3747: 
1.53      bowersj2 3748:     if ($dateStatus == ANSWER_OPEN) {
                   3749:         return ANSWER_OPEN;
1.51      bowersj2 3750:     }
                   3751: 
                   3752:     # Now: (incorrect, incorrect_override, not_attempted) x 
                   3753:     # (open_later), (open)
                   3754:     
1.53      bowersj2 3755:     if ($dateStatus == OPEN_LATER) {
                   3756:         return OPEN_LATER;
1.51      bowersj2 3757:     }
                   3758: 
                   3759:     # If it's WRONG...
1.53      bowersj2 3760:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
1.51      bowersj2 3761:         # and there are TRIES LEFT:
1.79      bowersj2 3762:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
1.53      bowersj2 3763:             return TRIES_LEFT;
1.51      bowersj2 3764:         }
1.185     bowersj2 3765:         return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
1.51      bowersj2 3766:     }
                   3767: 
                   3768:     # Otherwise, it's untried and open
1.53      bowersj2 3769:     return OPEN; 
1.191     bowersj2 3770: }
                   3771: 
                   3772: =pod
                   3773: 
                   3774: B<Completable>
                   3775: 
                   3776: The completable method represents the concept of I<whether the student can
                   3777: currently do the problem>. If the student can do the problem, which means
                   3778: that it is open, there are tries left, and if the problem is manually graded
                   3779: or the grade is suppressed via problemstatus, the student has not tried it
                   3780: yet, then the method returns 1. Otherwise, it returns 0, to indicate that 
                   3781: either the student has tried it and there is no feedback, or that for
                   3782: some reason it is no longer completable (not open yet, successfully completed,
                   3783: out of tries, etc.). As an example, this is used as the filter for the
                   3784: "Uncompleted Homework" option for the nav maps.
                   3785: 
                   3786: If this does not quite meet your needs, do not fiddle with it (unless you are
                   3787: fixing it to better match the student's conception of "completable" because
                   3788: it's broken somehow)... make a new method.
                   3789: 
                   3790: =cut
                   3791: 
                   3792: sub completable {
                   3793:     my $self = shift;
                   3794:     if (!$self->is_problem()) { return 0; }
                   3795:     my $partCount = $self->countParts();
                   3796: 
                   3797:     foreach my $part (@{$self->parts()}) {
                   3798:         if ($part eq '0' && $partCount != 1) { next; }
                   3799:         my $status = $self->status($part);
                   3800:         # "If any of the parts are open, or have tries left (implies open),
                   3801:         # and it is not "attempted" (manually graded problem), it is
                   3802:         # not "complete"
                   3803:         if (!(($status == OPEN() || $status == TRIES_LEFT()) 
                   3804:               && $self->getCompletionStatus($part) != ATTEMPTED()
                   3805:               && $status != ANSWER_SUBMITTED())) {
                   3806:             return 0;
                   3807:         }
                   3808:     }
                   3809:         
                   3810:     # If all the parts were complete, so was this problem.
                   3811:     return 1;
1.51      bowersj2 3812: }
                   3813: 
                   3814: =pod
                   3815: 
                   3816: =head2 Resource/Nav Map Navigation
                   3817: 
                   3818: =over 4
                   3819: 
1.174     albertel 3820: =item * B<getNext>():
                   3821: 
                   3822: Retreive an array of the possible next resources after this
                   3823: one. Always returns an array, even in the one- or zero-element case.
                   3824: 
                   3825: =item * B<getPrevious>():
1.85      bowersj2 3826: 
1.174     albertel 3827: Retreive an array of the possible previous resources from this
                   3828: one. Always returns an array, even in the one- or zero-element case.
1.51      bowersj2 3829: 
                   3830: =cut
                   3831: 
                   3832: sub getNext {
                   3833:     my $self = shift;
                   3834:     my @branches;
                   3835:     my $to = $self->to();
1.85      bowersj2 3836:     foreach my $branch ( split(/,/, $to) ) {
1.51      bowersj2 3837:         my $choice = $self->{NAV_MAP}->getById($branch);
                   3838:         my $next = $choice->goesto();
                   3839:         $next = $self->{NAV_MAP}->getById($next);
                   3840: 
1.131     bowersj2 3841:         push @branches, $next;
1.85      bowersj2 3842:     }
                   3843:     return \@branches;
                   3844: }
                   3845: 
                   3846: sub getPrevious {
                   3847:     my $self = shift;
                   3848:     my @branches;
                   3849:     my $from = $self->from();
                   3850:     foreach my $branch ( split /,/, $from) {
                   3851:         my $choice = $self->{NAV_MAP}->getById($branch);
                   3852:         my $prev = $choice->comesfrom();
                   3853:         $prev = $self->{NAV_MAP}->getById($prev);
                   3854: 
1.131     bowersj2 3855:         push @branches, $prev;
1.51      bowersj2 3856:     }
                   3857:     return \@branches;
1.131     bowersj2 3858: }
                   3859: 
                   3860: sub browsePriv {
                   3861:     my $self = shift;
                   3862:     if (defined($self->{BROWSE_PRIV})) {
                   3863:         return $self->{BROWSE_PRIV};
                   3864:     }
                   3865: 
                   3866:     $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
1.51      bowersj2 3867: }
                   3868: 
                   3869: =pod
1.2       www      3870: 
1.51      bowersj2 3871: =back
1.2       www      3872: 
1.51      bowersj2 3873: =cut
1.2       www      3874: 
1.51      bowersj2 3875: 1;
1.2       www      3876: 
1.51      bowersj2 3877: __END__
1.2       www      3878: 
                   3879: 

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