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

1.2       www         1: # The LearningOnline Network with CAPA
                      2: # Navigate Maps Handler
1.1       www         3: #
1.204   ! albertel    4: # $Id: lonnavmaps.pm,v 1.203 2003/06/13 13:58:06 bowersj2 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.95      bowersj2  164:     $r->print('<br>&nbsp;');
                    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
                    559: other modules
1.133     bowersj2  560: 
1.174     albertel  561: =head1 Object: 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
                    575: Apache::lonnavmaps::renderer->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
                    583: one or more of the preparent columns, and the renderer will assemble
                    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
                    601: Apache::lonnavmaps::renderer 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
                    609: the following parameter 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: 
                    868:         if (!$params->{'resource_no_folder_link'}) {
                    869:             $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') . '.gif';
                    870:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
                    871: 
                    872:             $linkopen = "<a href='" . $params->{'url'} . '?' . 
                    873:                 $params->{'queryString'} . '&filter=';
                    874:             $linkopen .= ($nowOpen xor $it->{CONDITION}) ?
                    875:                 addToFilter($filter, $mapId) :
                    876:                 removeFromFilter($filter, $mapId);
                    877:             $linkopen .= "&condition=" . $it->{CONDITION} . '&hereType='
                    878:                 . $params->{'hereType'} . '&here=' .
                    879:                 &Apache::lonnet::escape($params->{'here'}) . 
1.159     bowersj2  880:                 '&jump=' .
1.144     bowersj2  881:                 &Apache::lonnet::escape($resource->symb()) . 
                    882:                 "&folderManip=1'>";
                    883:         } else {
                    884:             # Don't allow users to manipulate folder
                    885:             $icon = 'navmap.folder.' . ($nowOpen ? 'closed' : 'open') .
                    886:                 '.nomanip.gif';
                    887:             $icon = "<img src='/adm/lonIcons/$icon' alt='' border='0' />";
                    888: 
                    889:             $linkopen = "";
                    890:             $linkclose = "";
                    891:         }
1.133     bowersj2  892:     }
1.51      bowersj2  893: 
1.133     bowersj2  894:     if ($resource->randomout()) {
                    895:         $nonLinkedText .= ' <i>(hidden)</i> ';
                    896:     }
                    897:     
                    898:     # We're done preparing and finally ready to start the rendering
                    899:     my $result = "<td align='left' valign='center'>";
1.140     bowersj2  900: 
                    901:     my $indentLevel = $params->{'indentLevel'};
                    902:     if ($newBranchText) { $indentLevel--; }
                    903: 
1.133     bowersj2  904:     # print indentation
1.140     bowersj2  905:     for (my $i = 0; $i < $indentLevel; $i++) {
1.133     bowersj2  906:         $result .= $params->{'indentString'};
1.84      bowersj2  907:     }
                    908: 
1.133     bowersj2  909:     # Decide what to display
                    910:     $result .= "$newBranchText$linkopen$icon$linkclose";
                    911:     
                    912:     my $curMarkerBegin = '';
                    913:     my $curMarkerEnd = '';
1.51      bowersj2  914: 
1.133     bowersj2  915:     # Is this the current resource?
1.158     bowersj2  916:     if (!$params->{'displayedHereMarker'} && 
                    917:         $resource->symb() eq $params->{'here'} ) {
1.133     bowersj2  918:         $curMarkerBegin = '<font color="red" size="+2">&gt; </font>';
                    919:         $curMarkerEnd = '<font color="red" size="+2">&lt;</font>';
1.158     bowersj2  920:         $params->{'displayedHereMarker'} = 1;
1.51      bowersj2  921:     }
                    922: 
1.192     bowersj2  923:     if ($resource->is_problem() && $part ne '0' && 
1.133     bowersj2  924:         !$params->{'condensed'}) {
                    925:         $partLabel = " (Part $part)";
                    926:         $title = "";
1.51      bowersj2  927:     }
                    928: 
1.163     bowersj2  929:     if ($params->{'condensed'} && $resource->countParts() > 1) {
1.133     bowersj2  930:         $nonLinkedText .= ' (' . $resource->countParts() . ' parts)';
1.51      bowersj2  931:     }
                    932: 
1.203     bowersj2  933:     if (!$params->{'resource_nolink'} && $src !~ /^\/uploaded\// &&
                    934: 	!$resource->is_map()) {
1.144     bowersj2  935:         $result .= "  $curMarkerBegin<a href='$link'>$title$partLabel</a>$curMarkerEnd $nonLinkedText</td>";
                    936:     } else {
                    937:         $result .= "  $curMarkerBegin$title$partLabel$curMarkerEnd $nonLinkedText</td>";
                    938:     }
1.51      bowersj2  939: 
1.133     bowersj2  940:     return $result;
                    941: }
1.51      bowersj2  942: 
1.133     bowersj2  943: sub render_communication_status {
                    944:     my ($resource, $part, $params) = @_;
1.134     bowersj2  945:     my $discussionHTML = ""; my $feedbackHTML = ""; my $errorHTML = "";
                    946: 
                    947:     my $link = $params->{"resourceLink"};
                    948:     my $linkopen = "<a href='$link'>";
                    949:     my $linkclose = "</a>";
                    950: 
                    951:     if ($resource->hasDiscussion()) {
                    952:         $discussionHTML = $linkopen .
                    953:             '<img border="0" src="/adm/lonMisc/chat.gif" />' .
                    954:             $linkclose;
                    955:     }
                    956:     
                    957:     if ($resource->getFeedback()) {
                    958:         my $feedback = $resource->getFeedback();
                    959:         foreach (split(/\,/, $feedback)) {
                    960:             if ($_) {
                    961:                 $feedbackHTML .= '&nbsp;<a href="/adm/email?display='
                    962:                     . &Apache::lonnet::escape($_) . '">'
                    963:                     . '<img src="/adm/lonMisc/feedback.gif" '
                    964:                     . 'border="0" /></a>';
                    965:             }
                    966:         }
                    967:     }
                    968:     
                    969:     if ($resource->getErrors()) {
                    970:         my $errors = $resource->getErrors();
                    971:         foreach (split(/,/, $errors)) {
                    972:             if ($_) {
                    973:                 $errorHTML .= '&nbsp;<a href="/adm/email?display='
                    974:                     . &Apache::lonnet::escape($_) . '">'
                    975:                     . '<img src="/adm/lonMisc/bomb.gif" '
                    976:                     . 'border="0" /></a>';
                    977:             }
                    978:         }
1.197     bowersj2  979:     }
                    980: 
                    981:     if ($params->{'multipart'} && $part != '0') {
                    982: 	$discussionHTML = $feedbackHTML = $errorHTML = '';
1.134     bowersj2  983:     }
                    984: 
                    985:     return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";
                    986: 
1.133     bowersj2  987: }
                    988: sub render_quick_status {
                    989:     my ($resource, $part, $params) = @_;
1.135     bowersj2  990:     my $result = "";
                    991:     my $firstDisplayed = !$params->{'condensed'} && 
                    992:         $params->{'multipart'} && $part eq "0";
                    993: 
                    994:     my $link = $params->{"resourceLink"};
                    995:     my $linkopen = "<a href='$link'>";
                    996:     my $linkclose = "</a>";
                    997: 
                    998:     if ($resource->is_problem() &&
                    999:         !$firstDisplayed) {
                   1000:         my $icon = $statusIconMap{$resource->status($part)};
                   1001:         my $alt = $iconAltTags{$icon};
                   1002:         if ($icon) {
                   1003:             $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";
                   1004:         } else {
                   1005:             $result .= "<td width='30'>&nbsp;</td>\n";
                   1006:         }
                   1007:     } else { # not problem, no icon
                   1008:         $result .= "<td width='30'>&nbsp;</td>\n";
                   1009:     }
                   1010: 
                   1011:     return $result;
1.133     bowersj2 1012: }
                   1013: sub render_long_status {
                   1014:     my ($resource, $part, $params) = @_;
1.136     bowersj2 1015:     my $result = "<td align='right' valign='center'>\n";
                   1016:     my $firstDisplayed = !$params->{'condensed'} && 
                   1017:         $params->{'multipart'} && $part eq "0";
                   1018:                 
                   1019:     my $color;
1.192     bowersj2 1020:     if ($resource->is_problem() && ($resource->countParts() <= 1 || $part ne '') ) {
1.136     bowersj2 1021:         $color = $colormap{$resource->status};
                   1022:         
                   1023:         if (dueInLessThen24Hours($resource, $part) ||
                   1024:             lastTry($resource, $part)) {
                   1025:             $color = $hurryUpColor;
                   1026:         }
                   1027:     }
                   1028:     
                   1029:     if ($resource->kind() eq "res" &&
                   1030:         $resource->is_problem() &&
                   1031:         !$firstDisplayed) {
                   1032:         if ($color) {$result .= "<font color=\"$color\"><b>"; }
                   1033:         $result .= getDescription($resource, $part);
                   1034:         if ($color) {$result .= "</b></font>"; }
                   1035:     }
                   1036:     if ($resource->is_map() && advancedUser() && $resource->randompick()) {
                   1037:         $result .= '(randomly select ' . $resource->randompick() .')';
                   1038:     }
                   1039:     
                   1040:     return $result;
1.51      bowersj2 1041: }
                   1042: 
1.133     bowersj2 1043: my @preparedColumns = (\&render_resource, \&render_communication_status,
                   1044:                        \&render_quick_status, \&render_long_status);
1.132     bowersj2 1045: 
                   1046: sub setDefault {
                   1047:     my ($val, $default) = @_;
                   1048:     if (!defined($val)) { return $default; }
                   1049:     return $val;
                   1050: }
                   1051: 
                   1052: sub render {
                   1053:     my $args = shift;
1.140     bowersj2 1054:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
                   1055:     my $result = '';
                   1056: 
1.132     bowersj2 1057:     # Configure the renderer.
                   1058:     my $cols = $args->{'cols'};
                   1059:     if (!defined($cols)) {
                   1060:         # no columns, no nav maps.
                   1061:         return '';
                   1062:     }
1.140     bowersj2 1063:     my $mustCloseNavMap = 0;
                   1064:     my $navmap;
                   1065:     if (defined($args->{'navmap'})) {
                   1066:         $navmap = $args->{'navmap'};
                   1067:     }
                   1068: 
1.158     bowersj2 1069:     my $r = $args->{'r'};
1.140     bowersj2 1070:     my $queryString = $args->{'queryString'};
1.159     bowersj2 1071:     my $jump = $args->{'jump'};
1.158     bowersj2 1072:     my $here = $args->{'here'};
1.153     bowersj2 1073:     my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
1.140     bowersj2 1074:     my $currentJumpDelta = 2; # change this to change how many resources are displayed
                   1075:                              # before the current resource when using #current
                   1076: 
                   1077:     # If we were passed 'here' information, we are not rendering
                   1078:     # after a folder manipulation, and we were not passed an
                   1079:     # iterator, make sure we open the folders to show the "here"
                   1080:     # marker
                   1081:     my $filterHash = {};
                   1082:     # Figure out what we're not displaying
                   1083:     foreach (split(/\,/, $ENV{"form.filter"})) {
                   1084:         if ($_) {
                   1085:             $filterHash->{$_} = "1";
                   1086:         }
                   1087:     }
                   1088: 
1.191     bowersj2 1089:     # Filter: Remember filter function and add our own filter: Refuse
                   1090:     # to show hidden resources unless the user can see them.
                   1091:     my $userCanSeeHidden = advancedUser();
                   1092:     my $filterFunc = setDefault($args->{'filterFunc'},
                   1093:                                 sub {return 1;});
                   1094:     if (!$userCanSeeHidden) {
                   1095:         # Without renaming the filterfunc, the server seems to go into
                   1096:         # an infinite loop
                   1097:         my $oldFilterFunc = $filterFunc;
                   1098:         $filterFunc = sub { my $res = shift; return !$res->randomout() && 
                   1099:                                 &$oldFilterFunc($res);};
                   1100:     }
                   1101: 
1.140     bowersj2 1102:     my $condition = 0;
                   1103:     if ($ENV{'form.condition'}) {
                   1104:         $condition = 1;
                   1105:     }
                   1106: 
                   1107:     if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
                   1108:         # Step 1: Check to see if we have a navmap
                   1109:         if (!defined($navmap)) {
1.171     bowersj2 1110:             $navmap = Apache::lonnavmaps::navmap->new(
1.140     bowersj2 1111:                         $ENV{"request.course.fn"}.".db",
                   1112:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
                   1113:             $mustCloseNavMap = 1;
                   1114:         }
                   1115:         $navmap->init();
                   1116: 
                   1117:         # Step two: Locate what kind of here marker is necessary
                   1118:         # Determine where the "here" marker is and where the screen jumps to.
                   1119: 
1.175     bowersj2 1120:         if ($ENV{'form.postsymb'}) {
                   1121:             $here = $jump = $ENV{'form.postsymb'};
1.140     bowersj2 1122:         } elsif ($ENV{'form.postdata'}) {
                   1123:             # couldn't find a symb, is there a URL?
                   1124:             my $currenturl = $ENV{'form.postdata'};
1.158     bowersj2 1125:             #$currenturl=~s/^http\:\/\///;
                   1126:             #$currenturl=~s/^[^\/]+//;
1.140     bowersj2 1127:             
1.158     bowersj2 1128:             $here = $jump = &Apache::lonnet::symbread($currenturl);
1.140     bowersj2 1129:         }
1.158     bowersj2 1130: 
1.140     bowersj2 1131:         # Step three: Ensure the folders are open
                   1132:         my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
                   1133:         my $depth = 1;
                   1134:         $mapIterator->next(); # discard the first BEGIN_MAP
                   1135:         my $curRes = $mapIterator->next();
                   1136:         my $found = 0;
                   1137:         
                   1138:         # We only need to do this if we need to open the maps to show the
                   1139:         # current position. This will change the counter so we can't count
                   1140:         # for the jump marker with this loop.
                   1141:         while ($depth > 0 && !$found) {
                   1142:             if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
                   1143:             if ($curRes == $mapIterator->END_MAP()) { $depth--; }
                   1144:             
1.158     bowersj2 1145:             if (ref($curRes) && $curRes->symb() eq $here) {
1.140     bowersj2 1146:                 my $mapStack = $mapIterator->getStack();
                   1147:                 
                   1148:                 # Ensure the parent maps are open
                   1149:                 for my $map (@{$mapStack}) {
                   1150:                     if ($condition) {
                   1151:                         undef $filterHash->{$map->map_pc()};
                   1152:                     } else {
                   1153:                         $filterHash->{$map->map_pc()} = 1;
                   1154:                     }
                   1155:                 }
                   1156:                 $found = 1;
                   1157:             }
                   1158:             
                   1159:             $curRes = $mapIterator->next();
                   1160:         }            
1.159     bowersj2 1161:     }        
1.140     bowersj2 1162: 
                   1163:     if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
                   1164:         # If this is a click on a folder or something, we want to preserve the "here"
                   1165:         # from the querystring, and get the new "jump" marker
                   1166:         $here = $ENV{'form.here'};
                   1167:         $jump = $ENV{'form.jump'};
                   1168:     } 
                   1169:     
1.132     bowersj2 1170:     my $it = $args->{'iterator'};
                   1171:     if (!defined($it)) {
1.140     bowersj2 1172:         # Construct a default iterator based on $ENV{'form.'} information
                   1173:         
                   1174:         # Step 1: Check to see if we have a navmap
                   1175:         if (!defined($navmap)) {
1.164     bowersj2 1176:             $navmap = Apache::lonnavmaps::navmap->new($r, 
1.140     bowersj2 1177:                         $ENV{"request.course.fn"}.".db",
                   1178:                         $ENV{"request.course.fn"}."_parms.db", 1, 1);
                   1179:             $mustCloseNavMap = 1;
                   1180:         }
                   1181:         # Paranoia: Make sure it's ready
                   1182:         $navmap->init();
                   1183: 
1.144     bowersj2 1184:         # See if we're being passed a specific map
                   1185:         if ($args->{'iterator_map'}) {
                   1186:             my $map = $args->{'iterator_map'};
1.145     bowersj2 1187:             $map = $navmap->getResourceByUrl($map);
1.144     bowersj2 1188:             my $firstResource = $map->map_start();
                   1189:             my $finishResource = $map->map_finish();
                   1190: 
                   1191:             $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
                   1192:         } else {
                   1193:             $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
                   1194:         }
1.132     bowersj2 1195:     }
                   1196:     
1.159     bowersj2 1197:     # (re-)Locate the jump point, if any
1.191     bowersj2 1198:     # Note this does not take filtering or hidden into account... need
                   1199:     # to be fixed?
1.159     bowersj2 1200:     my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
                   1201:     my $depth = 1;
                   1202:     $mapIterator->next();
                   1203:     my $curRes = $mapIterator->next();
                   1204:     my $foundJump = 0;
                   1205:     my $counter = 0;
                   1206:     
                   1207:     while ($depth > 0 && !$foundJump) {
                   1208:         if ($curRes == $mapIterator->BEGIN_MAP()) { $depth++; }
                   1209:         if ($curRes == $mapIterator->END_MAP()) { $depth--; }
                   1210:         if (ref($curRes)) { $counter++; }
                   1211:         
                   1212:         if (ref($curRes) && $jump eq $curRes->symb()) {
                   1213:             
                   1214:             # This is why we have to use the main iterator instead of the
                   1215:             # potentially faster DFS: The count has to be the same, so
                   1216:             # the order has to be the same, which DFS won't give us.
                   1217:             $args->{'currentJumpIndex'} = $counter;
                   1218:             $foundJump = 1;
                   1219:         }
                   1220:         
                   1221:         $curRes = $mapIterator->next();
                   1222:     }
                   1223: 
1.132     bowersj2 1224:     my $showParts = setDefault($args->{'showParts'}, 1);
                   1225:     my $condenseParts = setDefault($args->{'condenseParts'}, 1);
1.139     bowersj2 1226:     # keeps track of when the current resource is found,
                   1227:     # so we can back up a few and put the anchor above the
                   1228:     # current resource
1.140     bowersj2 1229:     my $printKey = $args->{'printKey'};
                   1230:     my $printCloseAll = $args->{'printCloseAll'};
                   1231:     if (!defined($printCloseAll)) { $printCloseAll = 1; }
1.144     bowersj2 1232:     
1.140     bowersj2 1233:     # Print key?
                   1234:     if ($printKey) {
                   1235:         $result .= '<table border="0" cellpadding="2" cellspacing="0">';
                   1236:         my $date=localtime;
                   1237:         $result.='<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>';
                   1238:         if ($navmap->{LAST_CHECK}) {
                   1239:             $result .= 
                   1240:                 '<img src="/adm/lonMisc/chat.gif"> New discussion since '.
                   1241:                 strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
                   1242:                 '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
                   1243:                 '<img src="/adm/lonMisc/feedback.gif"> New message (click to open)<p>'.
                   1244:                 '</td>'; 
                   1245:         } else {
                   1246:             $result .= '<td align="center" valign="bottom">&nbsp;&nbsp;'.
                   1247:                 '<img src="/adm/lonMisc/chat.gif"> Discussions</td><td align="center" valign="bottom">'.
                   1248:                 '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> New message (click to open)'.
                   1249:                 '</td>'; 
                   1250:         }
                   1251: 
                   1252:         $result .= '</tr></table>';
                   1253:     }
                   1254: 
1.172     bowersj2 1255:     if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
1.140     bowersj2 1256:         if ($condition) {
                   1257:             $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
1.158     bowersj2 1258:                 "&here=" . Apache::lonnet::escape($here) .
1.140     bowersj2 1259:                 "\">Close All Folders</a>";
                   1260:         } else {
                   1261:             $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
1.158     bowersj2 1262:                 "&here=" . Apache::lonnet::escape($here) . 
1.140     bowersj2 1263:                 "\">Open All Folders</a>";
                   1264:         }
1.143     bowersj2 1265:         $result .= "<br /><br />\n";
1.140     bowersj2 1266:     }    
                   1267: 
                   1268:     if ($r) {
                   1269:         $r->print($result);
                   1270:         $r->rflush();
                   1271:         $result = "";
                   1272:     }
1.132     bowersj2 1273:     # End parameter setting
1.133     bowersj2 1274:             
1.132     bowersj2 1275:     # Data
1.140     bowersj2 1276:     $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
1.132     bowersj2 1277:     my $res = "Apache::lonnavmaps::resource";
                   1278:     my %condenseStatuses =
                   1279:         ( $res->NETWORK_FAILURE    => 1,
                   1280:           $res->NOTHING_SET        => 1,
                   1281:           $res->CORRECT            => 1 );
                   1282:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
1.133     bowersj2 1283: 
                   1284:     # Shared variables
                   1285:     $args->{'counter'} = 0; # counts the rows
                   1286:     $args->{'indentLevel'} = 0;
                   1287:     $args->{'isNewBranch'} = 0;
                   1288:     $args->{'condensed'} = 0;    
                   1289:     $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
                   1290:     $args->{'displayedHereMarker'} = 0;
1.132     bowersj2 1291: 
1.190     bowersj2 1292:     # If we're suppressing empty sequences, look for them here. Use DFS for speed,
                   1293:     # since structure actually doesn't matter, except what map has what resources.
                   1294:     if ($args->{'suppressEmptySequences'}) {
                   1295:         my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
                   1296:                                                          $it->{FIRST_RESOURCE},
                   1297:                                                          $it->{FINISH_RESOURCE},
                   1298:                                                          {}, undef, 1);
                   1299:         $depth = 0;
                   1300:         $dfsit->next();
                   1301:         my $curRes = $dfsit->next();
                   1302:         while ($depth > -1) {
                   1303:             if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
                   1304:             if ($curRes == $dfsit->END_MAP()) { $depth--; }
                   1305: 
                   1306:             if (ref($curRes)) { 
                   1307:                 # Parallel pre-processing: Do sequences have non-filtered-out children?
1.201     bowersj2 1308:                 if ($curRes->is_map()) {
1.190     bowersj2 1309:                     $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
                   1310:                     # Sequences themselves do not count as visible children,
                   1311:                     # unless those sequences also have visible children.
                   1312:                     # This means if a sequence appears, there's a "promise"
                   1313:                     # that there's something under it if you open it, somewhere.
                   1314:                 } else {
                   1315:                     # Not a sequence: if it's filtered, ignore it, otherwise
                   1316:                     # rise up the stack and mark the sequences as having children
                   1317:                     if (&$filterFunc($curRes)) {
                   1318:                         for my $sequence (@{$dfsit->getStack()}) {
                   1319:                             $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
                   1320:                         }
                   1321:                     }
                   1322:                 }
                   1323:             }
                   1324:         } continue {
                   1325:             $curRes = $dfsit->next();
                   1326:         }
                   1327:     }
                   1328: 
1.133     bowersj2 1329:     my $displayedJumpMarker = 0;
1.132     bowersj2 1330:     # Set up iteration.
1.159     bowersj2 1331:     $depth = 1;
1.132     bowersj2 1332:     $it->next(); # discard initial BEGIN_MAP
1.159     bowersj2 1333:     $curRes = $it->next();
1.132     bowersj2 1334:     my $now = time();
                   1335:     my $in24Hours = $now + 24 * 60 * 60;
                   1336:     my $rownum = 0;
                   1337: 
1.141     bowersj2 1338:     # export "here" marker information
                   1339:     $args->{'here'} = $here;
                   1340: 
1.132     bowersj2 1341:     while ($depth > 0) {
                   1342:         if ($curRes == $it->BEGIN_MAP()) { $depth++; }
                   1343:         if ($curRes == $it->END_MAP()) { $depth--; }
                   1344: 
                   1345:         # Maintain indentation level.
                   1346:         if ($curRes == $it->BEGIN_MAP() ||
                   1347:             $curRes == $it->BEGIN_BRANCH() ) {
1.133     bowersj2 1348:             $args->{'indentLevel'}++;
1.132     bowersj2 1349:         }
                   1350:         if ($curRes == $it->END_MAP() ||
                   1351:             $curRes == $it->END_BRANCH() ) {
1.133     bowersj2 1352:             $args->{'indentLevel'}--;
1.132     bowersj2 1353:         }
                   1354:         # Notice new branches
                   1355:         if ($curRes == $it->BEGIN_BRANCH()) {
1.133     bowersj2 1356:             $args->{'isNewBranch'} = 1;
                   1357:         }
                   1358: 
                   1359:         # If this isn't an actual resource, continue on
                   1360:         if (!ref($curRes)) {
                   1361:             next;
1.132     bowersj2 1362:         }
1.133     bowersj2 1363: 
1.143     bowersj2 1364:         # If this has been filtered out, continue on
                   1365:         if (!(&$filterFunc($curRes))) {
                   1366:             $args->{'isNewBranch'} = 0; # Don't falsely remember this
                   1367:             next;
                   1368:         } 
1.132     bowersj2 1369: 
1.190     bowersj2 1370:         # If this is an empty sequence and we're filtering them, continue on
1.201     bowersj2 1371:         if ($curRes->is_map() && $args->{'suppressEmptySequences'} &&
1.190     bowersj2 1372:             !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) {
                   1373:             next;
                   1374:         }
                   1375: 
1.153     bowersj2 1376:         # If we're suppressing navmaps and this is a navmap, continue on
                   1377:         if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
                   1378:             next;
                   1379:         }
                   1380: 
1.191     bowersj2 1381:         $args->{'counter'}++;
                   1382: 
1.132     bowersj2 1383:         # Does it have multiple parts?
1.133     bowersj2 1384:         $args->{'multipart'} = 0;
                   1385:         $args->{'condensed'} = 0;
1.132     bowersj2 1386:         my @parts;
                   1387:             
                   1388:         # Decide what parts to show.
1.133     bowersj2 1389:         if ($curRes->is_problem() && $showParts) {
1.132     bowersj2 1390:             @parts = @{$curRes->parts()};
1.192     bowersj2 1391:             $args->{'multipart'} = $curRes->multipart();
1.132     bowersj2 1392:             
                   1393:             if ($condenseParts) { # do the condensation
                   1394:                 if (!$curRes->opendate("0")) {
1.162     bowersj2 1395:                     @parts = ();
1.133     bowersj2 1396:                     $args->{'condensed'} = 1;
1.132     bowersj2 1397:                 }
1.133     bowersj2 1398:                 if (!$args->{'condensed'}) {
1.132     bowersj2 1399:                     # Decide whether to condense based on similarity
1.192     bowersj2 1400:                     my $status = $curRes->status($parts[0]);
                   1401:                     my $due = $curRes->duedate($parts[0]);
                   1402:                     my $open = $curRes->opendate($parts[0]);
1.132     bowersj2 1403:                     my $statusAllSame = 1;
                   1404:                     my $dueAllSame = 1;
                   1405:                     my $openAllSame = 1;
1.192     bowersj2 1406:                     for (my $i = 1; $i < scalar(@parts); $i++) {
1.132     bowersj2 1407:                         if ($curRes->status($parts[$i]) != $status){
                   1408:                             $statusAllSame = 0;
                   1409:                         }
                   1410:                         if ($curRes->duedate($parts[$i]) != $due ) {
                   1411:                             $dueAllSame = 0;
                   1412:                         }
                   1413:                         if ($curRes->opendate($parts[$i]) != $open) {
                   1414:                             $openAllSame = 0;
                   1415:                         }
                   1416:                     }
                   1417:                     # $*allSame is true if all the statuses were
                   1418:                     # the same. Now, if they are all the same and
                   1419:                     # match one of the statuses to condense, or they
                   1420:                     # are all open with the same due date, or they are
                   1421:                     # all OPEN_LATER with the same open date, display the
                   1422:                     # status of the first non-zero part (to get the 'correct'
                   1423:                     # status right, since 0 is never 'correct' or 'open').
                   1424:                     if (($statusAllSame && defined($condenseStatuses{$status})) ||
                   1425:                         ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
                   1426:                         ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
1.192     bowersj2 1427:                         @parts = ($parts[0]);
1.133     bowersj2 1428:                         $args->{'condensed'} = 1;
1.132     bowersj2 1429:                     }
                   1430:                 }
1.198     bowersj2 1431: 		# Multipart problem with one part: always "condense" (happens
                   1432: 		#  to match the desirable behavior)
                   1433: 		if ($curRes->countParts() == 1) {
                   1434: 		    @parts = ($parts[0]);
                   1435: 		    $args->{'condensed'} = 1;
                   1436: 		}
1.132     bowersj2 1437:             }
1.157     bowersj2 1438:         } 
1.132     bowersj2 1439:             
                   1440:         # If the multipart problem was condensed, "forget" it was multipart
                   1441:         if (scalar(@parts) == 1) {
1.133     bowersj2 1442:             $args->{'multipart'} = 0;
1.192     bowersj2 1443:         } else {
                   1444:             # Add part 0 so we display it correctly.
                   1445:             unshift @parts, '0';
1.132     bowersj2 1446:         }
                   1447: 
                   1448:         # Now, we've decided what parts to show. Loop through them and
                   1449:         # show them.
1.192     bowersj2 1450:         foreach my $part (@parts) {
1.132     bowersj2 1451:             $rownum ++;
                   1452:             my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
                   1453:             
                   1454:             $result .= "  <tr bgcolor='$backgroundColor'>\n";
1.134     bowersj2 1455: 
                   1456:             # Set up some data about the parts that the cols might want
                   1457:             my $filter = $it->{FILTER};
                   1458:             my $stack = $it->getStack();
                   1459:             my $src = getLinkForResource($stack);
                   1460:             
                   1461:             my $srcHasQuestion = $src =~ /\?/;
                   1462:             $args->{"resourceLink"} = $src.
                   1463:                 ($srcHasQuestion?'&':'?') .
1.137     bowersj2 1464:                 'symb=' . &Apache::lonnet::escape($curRes->symb());
1.132     bowersj2 1465:             
                   1466:             # Now, display each column.
                   1467:             foreach my $col (@$cols) {
1.139     bowersj2 1468:                 my $colHTML = '';
                   1469:                 if (ref($col)) {
                   1470:                     $colHTML .= &$col($curRes, $part, $args);
                   1471:                 } else {
                   1472:                     $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
                   1473:                 }
1.132     bowersj2 1474: 
1.133     bowersj2 1475:                 # If this is the first column and it's time to print
                   1476:                 # the anchor, do so
                   1477:                 if ($col == $cols->[0] && 
                   1478:                     $args->{'counter'} == $args->{'currentJumpIndex'} - 
1.139     bowersj2 1479:                     $currentJumpDelta) {
                   1480:                     # Jam the anchor after the <td> tag;
                   1481:                     # necessary for valid HTML (which Mozilla requires)
                   1482:                     $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
1.133     bowersj2 1483:                     $displayedJumpMarker = 1;
                   1484:                 }
1.139     bowersj2 1485:                 $result .= $colHTML . "\n";
1.132     bowersj2 1486:             }
1.139     bowersj2 1487:             $result .= "    </tr>\n";
1.140     bowersj2 1488:             $args->{'isNewBranch'} = 0;
1.139     bowersj2 1489:         }
1.153     bowersj2 1490: 
1.139     bowersj2 1491:         if ($r && $rownum % 20 == 0) {
                   1492:             $r->print($result);
                   1493:             $result = "";
                   1494:             $r->rflush();
1.132     bowersj2 1495:         }
1.156     bowersj2 1496:     } continue {
1.132     bowersj2 1497:         $curRes = $it->next();
                   1498:     }
                   1499:     
1.134     bowersj2 1500:     # Print out the part that jumps to #curloc if it exists
1.159     bowersj2 1501:     # delay needed because the browser is processing the jump before
                   1502:     # it finishes rendering, so it goes to the wrong place!
                   1503:     # onload might be better, but this routine has no access to that.
                   1504:     # On mozilla, the 0-millisecond timeout seems to prevent this;
                   1505:     # it's quite likely this might fix other browsers, too, and 
                   1506:     # certainly won't hurt anything.
1.139     bowersj2 1507:     if ($displayedJumpMarker) {
1.159     bowersj2 1508:         $result .= "<script>setTimeout(\"location += '#curloc';\", 0)</script>\n";
1.134     bowersj2 1509:     }
                   1510: 
1.132     bowersj2 1511:     $result .= "</table>";
1.140     bowersj2 1512:     
                   1513:     if ($r) {
                   1514:         $r->print($result);
                   1515:         $result = "";
                   1516:         $r->rflush();
                   1517:     }
                   1518:         
1.175     bowersj2 1519:     if ($mustCloseNavMap) { $navmap->untieHashes(); } 
1.132     bowersj2 1520: 
                   1521:     return $result;
                   1522: }
                   1523: 
1.133     bowersj2 1524: 1;
                   1525: 
                   1526: package Apache::lonnavmaps::navmap;
                   1527: 
                   1528: =pod
                   1529: 
1.174     albertel 1530: lonnavmaps provides functions and objects for dealing with the
                   1531: compiled course hashes generated when a user enters the course, the
                   1532: Apache handler for the "Navigation Map" button, and a flexible
                   1533: prepared renderer for navigation maps that are easy to use anywhere.
                   1534: 
                   1535: =head1 Object: navmap
1.133     bowersj2 1536: 
1.174     albertel 1537: Encapsulating the compiled nav map
1.133     bowersj2 1538: 
1.174     albertel 1539: navmap is an object that encapsulates a compiled course map and
                   1540: provides a reasonable interface to it.
1.133     bowersj2 1541: 
1.174     albertel 1542: Most notably it provides a way to navigate the map sensibly and a
                   1543: flexible iterator that makes it easy to write various renderers based
                   1544: on nav maps.
1.133     bowersj2 1545: 
                   1546: You must obtain resource objects through the navmap object.
                   1547: 
                   1548: =head2 Methods
                   1549: 
                   1550: =over 4
                   1551: 
1.174     albertel 1552: =item * B<new>(navHashFile, parmHashFile, genCourseAndUserOptions,
                   1553:   genMailDiscussStatus):
1.133     bowersj2 1554: 
1.174     albertel 1555: Binds a new navmap object to the compiled nav map hash and parm hash
                   1556: given as filenames. genCourseAndUserOptions is a flag saying whether
                   1557: the course options and user options hash should be generated. This is
                   1558: for when you are using the parameters of the resources that require
                   1559: them; see documentation in resource object
                   1560: documentation. genMailDiscussStatus causes the nav map to retreive
                   1561: information about the email and discussion status of
                   1562: resources. Returns the navmap object if this is successful, or
                   1563: B<undef> if not. You must check for undef; errors will occur when you
                   1564: try to use the other methods otherwise.
                   1565: 
                   1566: =item * B<getIterator>(first, finish, filter, condition):
                   1567: 
                   1568: See iterator documentation below.
1.133     bowersj2 1569: 
                   1570: =cut
                   1571: 
                   1572: use strict;
                   1573: use GDBM_File;
                   1574: 
                   1575: sub new {
                   1576:     # magic invocation to create a class instance
                   1577:     my $proto = shift;
                   1578:     my $class = ref($proto) || $proto;
                   1579:     my $self = {};
                   1580: 
                   1581:     $self->{NAV_HASH_FILE} = shift;
                   1582:     $self->{PARM_HASH_FILE} = shift;
                   1583:     $self->{GENERATE_COURSE_USER_OPT} = shift;
                   1584:     $self->{GENERATE_EMAIL_DISCUSS_STATUS} = shift;
                   1585: 
                   1586:     # Resource cache stores navmap resources as we reference them. We generate
                   1587:     # them on-demand so we don't pay for creating resources unless we use them.
                   1588:     $self->{RESOURCE_CACHE} = {};
                   1589: 
                   1590:     # Network failure flag, if we accessed the course or user opt and
                   1591:     # failed
                   1592:     $self->{NETWORK_FAILURE} = 0;
                   1593: 
                   1594:     # tie the nav hash
                   1595: 
1.168     bowersj2 1596:     my %navmaphash;
                   1597:     my %parmhash;
                   1598:     if (!(tie(%navmaphash, 'GDBM_File', $self->{NAV_HASH_FILE},
1.133     bowersj2 1599:               &GDBM_READER(), 0640))) {
                   1600:         return undef;
                   1601:     }
                   1602:     
1.168     bowersj2 1603:     if (!(tie(%parmhash, 'GDBM_File', $self->{PARM_HASH_FILE},
1.133     bowersj2 1604:               &GDBM_READER(), 0640)))
                   1605:     {
1.170     matthew  1606:         untie %{$self->{PARM_HASH}};
1.133     bowersj2 1607:         return undef;
                   1608:     }
                   1609: 
1.199     bowersj2 1610:     $self->{NAV_HASH} = \%navmaphash;
1.168     bowersj2 1611:     $self->{PARM_HASH} = \%parmhash;
1.140     bowersj2 1612:     $self->{INITED} = 0;
1.133     bowersj2 1613: 
                   1614:     bless($self);
                   1615:         
                   1616:     return $self;
                   1617: }
                   1618: 
                   1619: sub init {
                   1620:     my $self = shift;
1.140     bowersj2 1621:     if ($self->{INITED}) { return; }
1.133     bowersj2 1622: 
                   1623:     # If the course opt hash and the user opt hash should be generated,
                   1624:     # generate them
                   1625:     if ($self->{GENERATE_COURSE_USER_OPT}) {
                   1626:         my $uname=$ENV{'user.name'};
                   1627:         my $udom=$ENV{'user.domain'};
                   1628:         my $uhome=$ENV{'user.home'};
                   1629:         my $cid=$ENV{'request.course.id'};
                   1630:         my $chome=$ENV{'course.'.$cid.'.home'};
                   1631:         my ($cdom,$cnum)=split(/\_/,$cid);
                   1632:         
                   1633:         my $userprefix=$uname.'_'.$udom.'_';
                   1634:         
                   1635:         my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
                   1636:         unless ($uhome eq 'no_host') { 
                   1637: # ------------------------------------------------- Get coursedata (if present)
                   1638:             unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
                   1639:                 my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
                   1640:                                                  ':resourcedata',$chome);
1.182     bowersj2 1641:                 # Check for network failure
                   1642:                 if ( $reply =~ /no.such.host/i || $reply =~ /con_lost/i) {
                   1643:                     $self->{NETWORK_FAILURE} = 1;
                   1644:                 } elsif ($reply!~/^error\:/) {
1.133     bowersj2 1645:                     $courserdatas{$cid}=$reply;
                   1646:                     $courserdatas{$cid.'.last_cache'}=time;
                   1647:                 }
                   1648:             }
                   1649:             foreach (split(/\&/,$courserdatas{$cid})) {
                   1650:                 my ($name,$value)=split(/\=/,$_);
                   1651:                 $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
                   1652:                     &Apache::lonnet::unescape($value);
                   1653:             }
                   1654: # --------------------------------------------------- Get userdata (if present)
                   1655:             unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
                   1656:                 my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
                   1657:                 if ($reply!~/^error\:/) {
                   1658:                     $userrdatas{$uname.'___'.$udom}=$reply;
                   1659:                     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
                   1660:                 }
                   1661:                 # check to see if network failed
                   1662:                 elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
                   1663:                 {
                   1664:                     $self->{NETWORK_FAILURE} = 1;
                   1665:                 }
                   1666:             }
                   1667:             foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
                   1668:                 my ($name,$value)=split(/\=/,$_);
                   1669:                 $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
                   1670:                     &Apache::lonnet::unescape($value);
                   1671:             }
                   1672:             $self->{COURSE_OPT} = \%courseopt;
                   1673:             $self->{USER_OPT} = \%useropt;
                   1674:         }
                   1675:     }   
                   1676: 
                   1677:     if ($self->{GENERATE_EMAIL_DISCUSS_STATUS}) {
                   1678:         my $cid=$ENV{'request.course.id'};
                   1679:         my ($cdom,$cnum)=split(/\_/,$cid);
                   1680:         
                   1681:         my %emailstatus = &Apache::lonnet::dump('email_status');
                   1682:         my $logoutTime = $emailstatus{'logout'};
                   1683:         my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
1.193     bowersj2 1684:         $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
1.133     bowersj2 1685:                                $courseLeaveTime : $logoutTime);
                   1686:         my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
                   1687:                                                    $cdom, $cnum);
                   1688:         my %feedback=();
                   1689:         my %error=();
                   1690:         my $keys = &Apache::lonnet::reply('keys:'.
                   1691:                                           $ENV{'user.domain'}.':'.
                   1692:                                           $ENV{'user.name'}.':nohist_email',
                   1693:                                           $ENV{'user.home'});
                   1694: 
                   1695:         foreach my $msgid (split(/\&/, $keys)) {
                   1696:             $msgid=&Apache::lonnet::unescape($msgid);
                   1697:             my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
                   1698:             if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
                   1699:                 my ($what,$url)=($1,$2);
                   1700:                 my %status=
                   1701:                     &Apache::lonnet::get('email_status',[$msgid]);
                   1702:                 if ($status{$msgid}=~/^error\:/) { 
                   1703:                     $status{$msgid}=''; 
                   1704:                 }
                   1705:                 
                   1706:                 if (($status{$msgid} eq 'new') || 
                   1707:                     (!$status{$msgid})) { 
                   1708:                     if ($what eq 'Error') {
                   1709:                         $error{$url}.=','.$msgid; 
                   1710:                     } else {
                   1711:                         $feedback{$url}.=','.$msgid;
                   1712:                     }
                   1713:                 }
                   1714:             }
                   1715:         }
                   1716:         
                   1717:         $self->{FEEDBACK} = \%feedback;
                   1718:         $self->{ERROR_MSG} = \%error; # what is this? JB
                   1719:         $self->{DISCUSSION_TIME} = \%discussiontime;
                   1720:         $self->{EMAIL_STATUS} = \%emailstatus;
                   1721:         
                   1722:     }    
                   1723: 
                   1724:     $self->{PARM_CACHE} = {};
1.140     bowersj2 1725:     $self->{INITED} = 1;
1.133     bowersj2 1726: }
                   1727: 
                   1728: # Internal function: Takes a key to look up in the nav hash and implements internal
                   1729: # memory caching of that key.
                   1730: sub navhash {
                   1731:     my $self = shift; my $key = shift;
                   1732:     return $self->{NAV_HASH}->{$key};
                   1733: }
                   1734: 
                   1735: # Checks to see if coursemap is defined, matching test in old lonnavmaps
                   1736: sub courseMapDefined {
                   1737:     my $self = shift;
                   1738:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
                   1739: 
                   1740:     my $firstres = $self->navhash("map_start_$uri");
                   1741:     my $lastres = $self->navhash("map_finish_$uri");
                   1742:     return $firstres && $lastres;
                   1743: }
                   1744: 
                   1745: sub getIterator {
                   1746:     my $self = shift;
                   1747:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
                   1748:                                                      shift, undef, shift);
                   1749:     return $iterator;
                   1750: }
                   1751: 
                   1752: # unties the hash when done
                   1753: sub untieHashes {
1.168     bowersj2 1754:     my $self = shift;
1.170     matthew  1755:     untie %{$self->{NAV_HASH}};
                   1756:     untie %{$self->{PARM_HASH}};
1.133     bowersj2 1757: }
                   1758: 
                   1759: # Private method: Does the given resource (as a symb string) have
                   1760: # current discussion? Returns 0 if chat/mail data not extracted.
                   1761: sub hasDiscussion {
                   1762:     my $self = shift;
                   1763:     my $symb = shift;
                   1764:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
                   1765: 
                   1766:     #return defined($self->{DISCUSSION_TIME}->{$symb});
                   1767:     return $self->{DISCUSSION_TIME}->{$symb} >
                   1768:            $self->{LAST_CHECK};
                   1769: }
                   1770: 
                   1771: # Private method: Does the given resource (as a symb string) have
                   1772: # current feedback? Returns the string in the feedback hash, which
                   1773: # will be false if it does not exist.
                   1774: sub getFeedback { 
                   1775:     my $self = shift;
                   1776:     my $symb = shift;
                   1777: 
                   1778:     if (!defined($self->{FEEDBACK})) { return ""; }
                   1779:     
                   1780:     return $self->{FEEDBACK}->{$symb};
                   1781: }
                   1782: 
                   1783: # Private method: Get the errors for that resource (by source).
                   1784: sub getErrors { 
                   1785:     my $self = shift;
                   1786:     my $src = shift;
                   1787:     
                   1788:     if (!defined($self->{ERROR_MSG})) { return ""; }
                   1789:     return $self->{ERROR_MSG}->{$src};
                   1790: }
                   1791: 
                   1792: =pod
                   1793: 
1.174     albertel 1794: =item * B<getById>(id):
                   1795: 
                   1796: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
                   1797: object for that resource. This method, or other methods that use it
                   1798: (as in the resource object) is the only proper way to obtain a
                   1799: resource object.
1.133     bowersj2 1800: 
1.194     bowersj2 1801: =item * B<getBySymb>(symb):
                   1802: 
                   1803: Based on the symb of the resource, get a resource object for that
                   1804: resource. This is one of the proper ways to get a resource object.
                   1805: 
                   1806: =item * B<getMapByMapPc>(map_pc):
                   1807: 
                   1808: Based on the map_pc of the resource, get a resource object for
                   1809: the given map. This is one of the proper ways to get a resource object.
                   1810: 
1.133     bowersj2 1811: =cut
                   1812: 
                   1813: # The strategy here is to cache the resource objects, and only construct them
                   1814: # as we use them. The real point is to prevent reading any more from the tied
                   1815: # hash then we have to, which should hopefully alleviate speed problems.
                   1816: # Caching is just an incidental detail I throw in because it makes sense.
                   1817: 
                   1818: sub getById {
                   1819:     my $self = shift;
                   1820:     my $id = shift;
                   1821: 
                   1822:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
                   1823:     {
                   1824:         return $self->{RESOURCE_CACHE}->{$id};
                   1825:     }
                   1826: 
                   1827:     # resource handles inserting itself into cache.
                   1828:     # Not clear why the quotes are necessary, but as of this
                   1829:     # writing it doesn't work without them.
                   1830:     return "Apache::lonnavmaps::resource"->new($self, $id);
1.132     bowersj2 1831: }
1.133     bowersj2 1832: 
1.172     bowersj2 1833: sub getBySymb {
                   1834:     my $self = shift;
                   1835:     my $symb = shift;
                   1836:     my ($mapUrl, $id, $filename) = split (/___/, $symb);
                   1837:     my $map = $self->getResourceByUrl($mapUrl);
                   1838:     return $self->getById($map->map_pc() . '.' . $id);
1.194     bowersj2 1839: }
                   1840: 
                   1841: sub getByMapPc {
                   1842:     my $self = shift;
                   1843:     my $map_pc = shift;
                   1844:     my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
                   1845:     $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
                   1846:     return $self->getById($map_id);
1.172     bowersj2 1847: }
                   1848: 
1.133     bowersj2 1849: =pod
                   1850: 
1.174     albertel 1851: =item * B<firstResource>():
                   1852: 
                   1853: Returns a resource object reference corresponding to the first
                   1854: resource in the navmap.
1.133     bowersj2 1855: 
                   1856: =cut
                   1857: 
                   1858: sub firstResource {
                   1859:     my $self = shift;
                   1860:     my $firstResource = $self->navhash('map_start_' .
                   1861:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
                   1862:     return $self->getById($firstResource);
1.132     bowersj2 1863: }
1.133     bowersj2 1864: 
                   1865: =pod
                   1866: 
1.174     albertel 1867: =item * B<finishResource>():
                   1868: 
                   1869: Returns a resource object reference corresponding to the last resource
                   1870: in the navmap.
1.133     bowersj2 1871: 
                   1872: =cut
                   1873: 
                   1874: sub finishResource {
                   1875:     my $self = shift;
                   1876:     my $firstResource = $self->navhash('map_finish_' .
                   1877:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
                   1878:     return $self->getById($firstResource);
1.132     bowersj2 1879: }
1.133     bowersj2 1880: 
                   1881: # Parmval reads the parm hash and cascades the lookups. parmval_real does
                   1882: # the actual lookup; parmval caches the results.
                   1883: sub parmval {
                   1884:     my $self = shift;
                   1885:     my ($what,$symb)=@_;
                   1886:     my $hashkey = $what."|||".$symb;
                   1887: 
                   1888:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
                   1889:         return $self->{PARM_CACHE}->{$hashkey};
                   1890:     }
                   1891: 
                   1892:     my $result = $self->parmval_real($what, $symb);
                   1893:     $self->{PARM_CACHE}->{$hashkey} = $result;
                   1894:     return $result;
1.132     bowersj2 1895: }
                   1896: 
1.133     bowersj2 1897: sub parmval_real {
                   1898:     my $self = shift;
                   1899:     my ($what,$symb) = @_;
                   1900: 
                   1901:     my $cid=$ENV{'request.course.id'};
                   1902:     my $csec=$ENV{'request.course.sec'};
                   1903:     my $uname=$ENV{'user.name'};
                   1904:     my $udom=$ENV{'user.domain'};
                   1905: 
                   1906:     unless ($symb) { return ''; }
                   1907:     my $result='';
                   1908: 
                   1909:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
                   1910: 
                   1911: # ----------------------------------------------------- Cascading lookup scheme
                   1912:     my $rwhat=$what;
                   1913:     $what=~s/^parameter\_//;
                   1914:     $what=~s/\_/\./;
                   1915: 
                   1916:     my $symbparm=$symb.'.'.$what;
                   1917:     my $mapparm=$mapname.'___(all).'.$what;
                   1918:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
                   1919: 
                   1920:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
                   1921:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
                   1922:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
                   1923: 
                   1924:     my $courselevel= $usercourseprefix.'.'.$what;
                   1925:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
                   1926:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
                   1927: 
                   1928:     my $useropt = $self->{USER_OPT};
                   1929:     my $courseopt = $self->{COURSE_OPT};
                   1930:     my $parmhash = $self->{PARM_HASH};
                   1931: 
                   1932: # ---------------------------------------------------------- first, check user
                   1933:     if ($uname and defined($useropt)) {
                   1934:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
                   1935:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
                   1936:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
                   1937:     }
                   1938: 
                   1939: # ------------------------------------------------------- second, check course
                   1940:     if ($csec and defined($courseopt)) {
                   1941:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
                   1942:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
                   1943:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
                   1944:     }
                   1945: 
                   1946:     if (defined($courseopt)) {
                   1947:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
                   1948:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
                   1949:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
                   1950:     }
                   1951: 
                   1952: # ----------------------------------------------------- third, check map parms
                   1953: 
                   1954:     my $thisparm=$$parmhash{$symbparm};
                   1955:     if (defined($thisparm)) { return $thisparm; }
                   1956: 
                   1957: # ----------------------------------------------------- fourth , check default
                   1958: 
                   1959:     my $default=&Apache::lonnet::metadata($fn,$rwhat.'.default');
                   1960:     if (defined($default)) { return $default}
                   1961: 
                   1962: # --------------------------------------------------- fifth , cascade up parts
                   1963: 
                   1964:     my ($space,@qualifier)=split(/\./,$rwhat);
                   1965:     my $qualifier=join('.',@qualifier);
                   1966:     unless ($space eq '0') {
1.160     albertel 1967: 	my @parts=split(/_/,$space);
                   1968: 	my $id=pop(@parts);
                   1969: 	my $part=join('_',@parts);
                   1970: 	if ($part eq '') { $part='0'; }
                   1971: 	my $partgeneral=$self->parmval($part.".$qualifier",$symb);
                   1972: 	if (defined($partgeneral)) { return $partgeneral; }
1.133     bowersj2 1973:     }
                   1974:     return '';
1.145     bowersj2 1975: }
                   1976: 
1.174     albertel 1977: =pod
1.145     bowersj2 1978: 
1.174     albertel 1979: =item * B<getResourceByUrl>(url):
1.145     bowersj2 1980: 
1.174     albertel 1981: Retrieves a resource object by URL of the resource. If passed a
                   1982: resource object, it will simply return it, so it is safe to use this
                   1983: method in code like "$res = $navmap->getResourceByUrl($res)", if
                   1984: you're not sure if $res is already an object, or just a URL. If the
                   1985: resource appears multiple times in the course, only the first instance
                   1986: will be returned. As a result, this is probably useful only for maps.
                   1987: 
                   1988: =item * B<retrieveResources>(map, filterFunc, recursive, bailout):
                   1989: 
                   1990: The map is a specification of a map to retreive the resources from,
                   1991: either as a url or as an object. The filterFunc is a reference to a
                   1992: function that takes a resource object as its one argument and returns
                   1993: true if the resource should be included, or false if it should not
                   1994: be. If recursive is true, the map will be recursively examined,
                   1995: otherwise it will not be. If bailout is true, the function will return
                   1996: as soon as it finds a resource, if false it will finish. By default,
                   1997: the map is the top-level map of the course, filterFunc is a function
                   1998: that always returns 1, recursive is true, bailout is false. The
                   1999: resources will be returned in a list containing the resource objects
                   2000: for the corresponding resources, with B<no structure information> in
                   2001: the list; regardless of branching, recursion, etc., it will be a flat
                   2002: list.
                   2003: 
                   2004: Thus, this is suitable for cases where you don't want the structure,
                   2005: just a list of all resources. It is also suitable for finding out how
                   2006: many resources match a given description; for this use, if all you
                   2007: want to know is if I<any> resources match the description, the bailout
                   2008: parameter will allow you to avoid potentially expensive enumeration of
                   2009: all matching resources.
1.145     bowersj2 2010: 
1.174     albertel 2011: =item * B<hasResources>(map, filterFunc, recursive):
1.145     bowersj2 2012: 
1.174     albertel 2013: Convience method for
1.146     bowersj2 2014: 
                   2015:  scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
                   2016: 
1.174     albertel 2017: which will tell whether the map has resources matching the description
                   2018: in the filter function.
1.146     bowersj2 2019: 
1.145     bowersj2 2020: =cut
                   2021: 
                   2022: sub getResourceByUrl {
                   2023:     my $self = shift;
                   2024:     my $resUrl = shift;
                   2025: 
                   2026:     if (ref($resUrl)) { return $resUrl; }
                   2027: 
                   2028:     $resUrl = &Apache::lonnet::clutter($resUrl);
                   2029:     my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
                   2030:     if ($resId =~ /,/) {
                   2031:         $resId = (split (/,/, $resId))[0];
                   2032:     }
                   2033:     if (!$resId) { return ''; }
                   2034:     return $self->getById($resId);
                   2035: }
                   2036: 
                   2037: sub retrieveResources {
                   2038:     my $self = shift;
                   2039:     my $map = shift;
                   2040:     my $filterFunc = shift;
                   2041:     if (!defined ($filterFunc)) {
                   2042:         $filterFunc = sub {return 1;};
                   2043:     }
                   2044:     my $recursive = shift;
                   2045:     if (!defined($recursive)) { $recursive = 1; }
                   2046:     my $bailout = shift;
                   2047:     if (!defined($bailout)) { $bailout = 0; }
                   2048: 
                   2049:     # Create the necessary iterator.
                   2050:     if (!ref($map)) { # assume it's a url of a map.
1.172     bowersj2 2051:         $map = $self->getResourceByUrl($map);
1.145     bowersj2 2052:     }
                   2053: 
                   2054:     # Check the map's validity.
                   2055:     if (!$map || !$map->is_map()) {
                   2056:         # Oh, to throw an exception.... how I'd love that!
                   2057:         return ();
                   2058:     }
                   2059: 
1.146     bowersj2 2060:     # Get an iterator.
                   2061:     my $it = $self->getIterator($map->map_start(), $map->map_finish(),
                   2062:                                 !$recursive);
                   2063: 
                   2064:     my @resources = ();
                   2065: 
                   2066:     # Run down the iterator and collect the resources.
                   2067:     my $depth = 1;
                   2068:     $it->next();
                   2069:     my $curRes = $it->next();
                   2070: 
                   2071:     while ($depth > 0) {
                   2072:         if ($curRes == $it->BEGIN_MAP()) {
                   2073:             $depth++;
                   2074:         }
                   2075:         if ($curRes == $it->END_MAP()) {
                   2076:             $depth--;
                   2077:         }
                   2078:         
                   2079:         if (ref($curRes)) {
                   2080:             if (!&$filterFunc($curRes)) {
                   2081:                 next;
                   2082:             }
                   2083: 
                   2084:             push @resources, $curRes;
                   2085: 
                   2086:             if ($bailout) {
                   2087:                 return @resources;
                   2088:             }
                   2089:         }
                   2090: 
                   2091:         $curRes = $it->next();
                   2092:     }
                   2093: 
                   2094:     return @resources;
                   2095: }
                   2096: 
                   2097: sub hasResource {
                   2098:     my $self = shift;
                   2099:     my $map = shift;
                   2100:     my $filterFunc = shift;
                   2101:     my $recursive = shift;
                   2102:     
                   2103:     return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
1.133     bowersj2 2104: }
1.51      bowersj2 2105: 
                   2106: 1;
                   2107: 
                   2108: package Apache::lonnavmaps::iterator;
                   2109: 
                   2110: =pod
                   2111: 
                   2112: =back
                   2113: 
1.174     albertel 2114: =head1 Object: navmap Iterator
1.51      bowersj2 2115: 
1.174     albertel 2116: An I<iterator> encapsulates the logic required to traverse a data
                   2117: structure. navmap uses an iterator to traverse the course map
                   2118: according to the criteria you wish to use.
                   2119: 
                   2120: To obtain an iterator, call the B<getIterator>() function of a
                   2121: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
                   2122: directly.) This will return a reference to the iterator:
1.51      bowersj2 2123: 
                   2124: C<my $resourceIterator = $navmap-E<gt>getIterator();>
                   2125: 
                   2126: To get the next thing from the iterator, call B<next>:
                   2127: 
                   2128: C<my $nextThing = $resourceIterator-E<gt>next()>
                   2129: 
                   2130: getIterator behaves as follows:
                   2131: 
                   2132: =over 4
                   2133: 
1.174     albertel 2134: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
                   2135: 
                   2136: All parameters are optional. firstResource is a resource reference
                   2137: corresponding to where the iterator should start. It defaults to
                   2138: navmap->firstResource() for the corresponding nav map. finishResource
                   2139: corresponds to where you want the iterator to end, defaulting to
                   2140: navmap->finishResource(). filterHash is a hash used as a set
                   2141: containing strings representing the resource IDs, defaulting to
                   2142: empty. Condition is a 1 or 0 that sets what to do with the filter
                   2143: hash: If a 0, then only resource that exist IN the filterHash will be
                   2144: recursed on. If it is a 1, only resources NOT in the filterHash will
                   2145: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
                   2146: false (default), the iterator will only return the first level of map
                   2147: that is not just a single, 'redirecting' map. If true, the iterator
                   2148: will return all information, starting with the top-level map,
                   2149: regardless of content. returnTopMap, if true (default false), will
                   2150: cause the iterator to return the top-level map object (resource 0.0)
                   2151: before anything else.
                   2152: 
                   2153: Thus, by default, only top-level resources will be shown. Change the
                   2154: condition to a 1 without changing the hash, and all resources will be
                   2155: shown. Changing the condition to 1 and including some values in the
                   2156: hash will allow you to selectively suppress parts of the navmap, while
                   2157: leaving it on 0 and adding things to the hash will allow you to
                   2158: selectively add parts of the nav map. See the handler code for
                   2159: examples.
                   2160: 
                   2161: The iterator will return either a reference to a resource object, or a
                   2162: token representing something in the map, such as the beginning of a
                   2163: new branch. The possible tokens are:
                   2164: 
                   2165: =over 4
1.51      bowersj2 2166: 
1.174     albertel 2167: =item * BEGIN_MAP:
1.51      bowersj2 2168: 
1.174     albertel 2169: A new map is being recursed into. This is returned I<after> the map
                   2170: resource itself is returned.
1.51      bowersj2 2171: 
1.174     albertel 2172: =item * END_MAP:
                   2173: 
                   2174: The map is now done.
1.51      bowersj2 2175: 
1.174     albertel 2176: =item * BEGIN_BRANCH:
1.70      bowersj2 2177: 
1.174     albertel 2178: A branch is now starting. The next resource returned will be the first
                   2179: in that branch.
1.70      bowersj2 2180: 
1.174     albertel 2181: =item * END_BRANCH:
1.70      bowersj2 2182: 
1.174     albertel 2183: The branch is now done.
1.51      bowersj2 2184: 
                   2185: =back
                   2186: 
1.174     albertel 2187: The tokens are retreivable via methods on the iterator object, i.e.,
                   2188: $iterator->END_MAP.
1.70      bowersj2 2189: 
1.174     albertel 2190: Maps can contain empty resources. The iterator will automatically skip
                   2191: over such resources, but will still treat the structure
                   2192: correctly. Thus, a complicated map with several branches, but
                   2193: consisting entirely of empty resources except for one beginning or
                   2194: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
                   2195: but only one resource will be returned.
1.116     bowersj2 2196: 
1.70      bowersj2 2197: =back
1.51      bowersj2 2198: 
                   2199: =cut
                   2200: 
                   2201: # Here are the tokens for the iterator:
                   2202: 
                   2203: sub BEGIN_MAP { return 1; }    # begining of a new map
                   2204: sub END_MAP { return 2; }      # end of the map
                   2205: sub BEGIN_BRANCH { return 3; } # beginning of a branch
                   2206: sub END_BRANCH { return 4; }   # end of a branch
1.89      bowersj2 2207: sub FORWARD { return 1; }      # go forward
                   2208: sub BACKWARD { return 2; }
1.51      bowersj2 2209: 
1.96      bowersj2 2210: sub min {
                   2211:     (my $a, my $b) = @_;
                   2212:     if ($a < $b) { return $a; } else { return $b; }
                   2213: }
                   2214: 
1.107     bowersj2 2215: # In the CVS repository, documentation of this algorithm is included 
                   2216: # in /doc/lonnavdocs, as a PDF and .tex source. Markers like **1**
                   2217: # will reference the same location in the text as the part of the
                   2218: # algorithm is running through.
                   2219: 
1.94      bowersj2 2220: sub new {
                   2221:     # magic invocation to create a class instance
                   2222:     my $proto = shift;
                   2223:     my $class = ref($proto) || $proto;
                   2224:     my $self = {};
                   2225: 
                   2226:     $self->{NAV_MAP} = shift;
                   2227:     return undef unless ($self->{NAV_MAP});
                   2228: 
                   2229:     # Handle the parameters
                   2230:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
                   2231:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
                   2232: 
                   2233:     # If the given resources are just the ID of the resource, get the
                   2234:     # objects
                   2235:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
                   2236:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
                   2237:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
                   2238:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
                   2239: 
                   2240:     $self->{FILTER} = shift;
                   2241: 
                   2242:     # A hash, used as a set, of resource already seen
                   2243:     $self->{ALREADY_SEEN} = shift;
                   2244:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
                   2245:     $self->{CONDITION} = shift;
                   2246: 
1.116     bowersj2 2247:     # Do we want to automatically follow "redirection" maps?
                   2248:     $self->{FORCE_TOP} = shift;
                   2249: 
1.162     bowersj2 2250:     # Do we want to return the top-level map object (resource 0.0)?
                   2251:     $self->{RETURN_0} = shift;
                   2252:     # have we done that yet?
                   2253:     $self->{HAVE_RETURNED_0} = 0;
                   2254: 
1.94      bowersj2 2255:     # Now, we need to pre-process the map, by walking forward and backward
                   2256:     # over the parts of the map we're going to look at.
1.96      bowersj2 2257: 
1.97      bowersj2 2258:     # The processing steps are exactly the same, except for a few small 
                   2259:     # changes, so I bundle those up in the following list of two elements:
                   2260:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
                   2261:     # first_resource).
                   2262:     # This prevents writing nearly-identical code twice.
                   2263:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
                   2264:                         'FIRST_RESOURCE'],
                   2265:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
                   2266:                         'FINISH_RESOURCE'] );
                   2267: 
1.98      bowersj2 2268:     my $maxDepth = 0; # tracks max depth
                   2269: 
1.116     bowersj2 2270:     # If there is only one resource in this map, and it's a map, we
                   2271:     # want to remember that, so the user can ask for the first map
                   2272:     # that isn't just a redirector.
                   2273:     my $resource; my $resourceCount = 0;
                   2274: 
1.107     bowersj2 2275:     # **1**
                   2276: 
1.97      bowersj2 2277:     foreach my $pass (@iterations) {
                   2278:         my $direction = $pass->[0];
                   2279:         my $valName = $pass->[1];
                   2280:         my $nextResourceMethod = $pass->[2];
                   2281:         my $firstResourceName = $pass->[3];
                   2282: 
                   2283:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
                   2284:                                                             $self->{FIRST_RESOURCE},
                   2285:                                                             $self->{FINISH_RESOURCE},
                   2286:                                                             {}, undef, 0, $direction);
1.96      bowersj2 2287:     
1.97      bowersj2 2288:         # prime the recursion
                   2289:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
1.98      bowersj2 2290:         my $depth = 0;
1.97      bowersj2 2291:         $iterator->next();
                   2292:         my $curRes = $iterator->next();
1.98      bowersj2 2293:         while ($depth > -1) {
1.97      bowersj2 2294:             if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
                   2295:             if ($curRes == $iterator->END_MAP()) { $depth--; }
1.96      bowersj2 2296:         
1.97      bowersj2 2297:             if (ref($curRes)) {
1.116     bowersj2 2298:                 # If there's only one resource, this will save it
1.117     bowersj2 2299:                 # we have to filter empty resources from consideration here,
                   2300:                 # or even "empty", redirecting maps have two (start & finish)
                   2301:                 # or three (start, finish, plus redirector)
                   2302:                 if($direction == FORWARD && $curRes->src()) { 
                   2303:                     $resource = $curRes; $resourceCount++; 
                   2304:                 }
1.97      bowersj2 2305:                 my $resultingVal = $curRes->{DATA}->{$valName};
                   2306:                 my $nextResources = $curRes->$nextResourceMethod();
1.116     bowersj2 2307:                 my $nextCount = scalar(@{$nextResources});
1.104     bowersj2 2308: 
1.116     bowersj2 2309:                 if ($nextCount == 1) { # **3**
1.97      bowersj2 2310:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
                   2311:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
                   2312:                 }
                   2313:                 
1.116     bowersj2 2314:                 if ($nextCount > 1) { # **4**
1.97      bowersj2 2315:                     foreach my $res (@{$nextResources}) {
                   2316:                         my $current = $res->{DATA}->{$valName} || 999999999;
                   2317:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
                   2318:                     }
                   2319:                 }
                   2320:             }
1.96      bowersj2 2321:             
1.107     bowersj2 2322:             # Assign the final val (**2**)
1.97      bowersj2 2323:             if (ref($curRes) && $direction == BACKWARD()) {
1.98      bowersj2 2324:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
                   2325:                                      $curRes->{DATA}->{BOT_UP_VAL});
                   2326:                 
                   2327:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
                   2328:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
1.190     bowersj2 2329:             }
                   2330:         } continue {
1.97      bowersj2 2331:             $curRes = $iterator->next();
1.96      bowersj2 2332:         }
                   2333:     }
1.94      bowersj2 2334: 
1.116     bowersj2 2335:     # Check: Was this only one resource, a map?
                   2336:     if ($resourceCount == 1 && $resource->is_map() && !$self->{FORCE_TOP}) { 
                   2337:         my $firstResource = $resource->map_start();
                   2338:         my $finishResource = $resource->map_finish();
                   2339:         return 
                   2340:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                   2341:                                               $finishResource, $self->{FILTER},
                   2342:                                               $self->{ALREADY_SEEN}, 
                   2343:                                               $self->{CONDITION}, 0);
                   2344:         
                   2345:     }
                   2346: 
1.98      bowersj2 2347:     # Set up some bookkeeping information.
                   2348:     $self->{CURRENT_DEPTH} = 0;
                   2349:     $self->{MAX_DEPTH} = $maxDepth;
                   2350:     $self->{STACK} = [];
                   2351:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2352: 
                   2353:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
                   2354:         push @{$self->{STACK}}, [];
                   2355:     }
                   2356: 
1.107     bowersj2 2357:     # Prime the recursion w/ the first resource **5**
1.98      bowersj2 2358:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
                   2359:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
                   2360: 
                   2361:     bless ($self);
                   2362: 
                   2363:     return $self;
                   2364: }
                   2365: 
                   2366: sub next {
                   2367:     my $self = shift;
1.162     bowersj2 2368: 
                   2369:     # If we want to return the top-level map object, and haven't yet,
                   2370:     # do so.
                   2371:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
                   2372:         $self->{HAVE_RETURNED_0} = 1;
                   2373:         return $self->{NAV_MAP}->getById('0.0');
                   2374:     }
1.98      bowersj2 2375: 
                   2376:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2377:         # grab the next from the recursive iterator 
                   2378:         my $next = $self->{RECURSIVE_ITERATOR}->next();
                   2379: 
                   2380:         # is it a begin or end map? If so, update the depth
                   2381:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
                   2382:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
                   2383: 
                   2384:         # Are we back at depth 0? If so, stop recursing
                   2385:         if ($self->{RECURSIVE_DEPTH} == 0) {
                   2386:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2387:         }
                   2388: 
                   2389:         return $next;
                   2390:     }
                   2391: 
                   2392:     if (defined($self->{FORCE_NEXT})) {
                   2393:         my $tmp = $self->{FORCE_NEXT};
                   2394:         $self->{FORCE_NEXT} = undef;
                   2395:         return $tmp;
                   2396:     }
                   2397: 
                   2398:     # Have we not yet begun? If not, return BEGIN_MAP and
                   2399:     # remember we've started.
                   2400:     if ( !$self->{STARTED} ) { 
                   2401:         $self->{STARTED} = 1;
                   2402:         return $self->BEGIN_MAP();
                   2403:     }
                   2404: 
                   2405:     # Here's the guts of the iterator.
                   2406:     
                   2407:     # Find the next resource, if any.
                   2408:     my $found = 0;
                   2409:     my $i = $self->{MAX_DEPTH};
                   2410:     my $newDepth;
                   2411:     my $here;
                   2412:     while ( $i >= 0 && !$found ) {
1.107     bowersj2 2413:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
                   2414:             $here = pop @{$self->{STACK}->[$i]}; # **7**
1.98      bowersj2 2415:             $found = 1;
                   2416:             $newDepth = $i;
                   2417:         }
                   2418:         $i--;
                   2419:     }
                   2420: 
                   2421:     # If we still didn't find anything, we're done.
                   2422:     if ( !$found ) {
                   2423:         # We need to get back down to the correct branch depth
                   2424:         if ( $self->{CURRENT_DEPTH} > 0 ) {
                   2425:             $self->{CURRENT_DEPTH}--;
                   2426:             return END_BRANCH();
                   2427:         } else {
                   2428:             return END_MAP();
                   2429:         }
                   2430:     }
                   2431: 
1.104     bowersj2 2432:     # If this is not a resource, it must be an END_BRANCH marker we want
                   2433:     # to return directly.
1.107     bowersj2 2434:     if (!ref($here)) { # **8**
1.104     bowersj2 2435:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
                   2436:             $self->{CURRENT_DEPTH}--;
                   2437:             return $here;
                   2438:         }
                   2439:     }
                   2440: 
                   2441:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
                   2442:     $self->{HERE} = $here;
                   2443: 
1.98      bowersj2 2444:     # Get to the right level
                   2445:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
                   2446:         push @{$self->{STACK}->[$newDepth]}, $here;
                   2447:         $self->{CURRENT_DEPTH}--;
                   2448:         return END_BRANCH();
                   2449:     }
                   2450:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
                   2451:         push @{$self->{STACK}->[$newDepth]}, $here;
                   2452:         $self->{CURRENT_DEPTH}++;
                   2453:         return BEGIN_BRANCH();
                   2454:     }
                   2455: 
                   2456:     # If we made it here, we have the next resource, and we're at the
                   2457:     # right branch level. So let's examine the resource for where
                   2458:     # we can get to from here.
                   2459: 
                   2460:     # So we need to look at all the resources we can get to from here,
                   2461:     # categorize them if we haven't seen them, remember if we have a new
                   2462:     my $nextUnfiltered = $here->getNext();
1.104     bowersj2 2463:     my $maxDepthAdded = -1;
                   2464:     
1.98      bowersj2 2465:     for (@$nextUnfiltered) {
                   2466:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1.104     bowersj2 2467:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
                   2468:             push @{$self->{STACK}->[$depth]}, $_;
1.98      bowersj2 2469:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
1.104     bowersj2 2470:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
1.98      bowersj2 2471:         }
                   2472:     }
1.104     bowersj2 2473: 
                   2474:     # Is this the end of a branch? If so, all of the resources examined above
                   2475:     # led to lower levels then the one we are currently at, so we push a END_BRANCH
                   2476:     # marker onto the stack so we don't forget.
                   2477:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
                   2478:     # BC branch and gets to C, it will see F as the only next resource, but it's
                   2479:     # one level lower. Thus, this is the end of the branch, since there are no
                   2480:     # more resources added to this level or above.
1.111     bowersj2 2481:     # We don't do this if the examined resource is the finish resource,
                   2482:     # because the condition given above is true, but the "END_MAP" will
                   2483:     # take care of things and we should already be at depth 0.
1.104     bowersj2 2484:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
1.111     bowersj2 2485:     if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
1.104     bowersj2 2486:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
                   2487:     }
                   2488: 
1.98      bowersj2 2489:     # That ends the main iterator logic. Now, do we want to recurse
                   2490:     # down this map (if this resource is a map)?
                   2491:     if ($self->{HERE}->is_map() &&
                   2492:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
                   2493:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
                   2494:         my $firstResource = $self->{HERE}->map_start();
                   2495:         my $finishResource = $self->{HERE}->map_finish();
                   2496: 
                   2497:         $self->{RECURSIVE_ITERATOR} = 
                   2498:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                   2499:                                               $finishResource, $self->{FILTER},
                   2500:                                               $self->{ALREADY_SEEN}, $self->{CONDITION});
                   2501:     }
                   2502: 
1.116     bowersj2 2503:     # If this is a blank resource, don't actually return it.
1.117     bowersj2 2504:     # Should you ever find you need it, make sure to add an option to the code
                   2505:     #  that you can use; other things depend on this behavior.
1.138     bowersj2 2506:     my $browsePriv = $self->{HERE}->browsePriv();
                   2507:     if (!$self->{HERE}->src() || 
                   2508:         (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
1.116     bowersj2 2509:         return $self->next();
                   2510:     }
                   2511: 
1.98      bowersj2 2512:     return $self->{HERE};
                   2513: 
                   2514: }
                   2515: 
                   2516: =pod
                   2517: 
1.174     albertel 2518: The other method available on the iterator is B<getStack>, which
                   2519: returns an array populated with the current 'stack' of maps, as
                   2520: references to the resource objects. Example: This is useful when
                   2521: making the navigation map, as we need to check whether we are under a
                   2522: page map to see if we need to link directly to the resource, or to the
                   2523: page. The first elements in the array will correspond to the top of
                   2524: the stack (most inclusive map).
1.98      bowersj2 2525: 
                   2526: =cut
                   2527: 
                   2528: sub getStack {
                   2529:     my $self=shift;
                   2530: 
                   2531:     my @stack;
                   2532: 
                   2533:     $self->populateStack(\@stack);
                   2534: 
                   2535:     return \@stack;
                   2536: }
                   2537: 
                   2538: # Private method: Calls the iterators recursively to populate the stack.
                   2539: sub populateStack {
                   2540:     my $self=shift;
                   2541:     my $stack = shift;
                   2542: 
                   2543:     push @$stack, $self->{HERE} if ($self->{HERE});
                   2544: 
                   2545:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2546:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
                   2547:     }
1.94      bowersj2 2548: }
                   2549: 
                   2550: 1;
                   2551: 
                   2552: package Apache::lonnavmaps::DFSiterator;
                   2553: 
1.100     bowersj2 2554: # Not documented in the perldoc: This is a simple iterator that just walks
                   2555: #  through the nav map and presents the resources in a depth-first search
                   2556: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
                   2557: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
                   2558: #  useful for pre-processing of some kind, and is in fact used by the main
                   2559: #  iterator that way, but that's about it.
                   2560: # One could imagine merging this into the init routine of the main iterator,
                   2561: #  but this might as well be left seperate, since it is possible some other
                   2562: #  use might be found for it. - Jeremy
1.94      bowersj2 2563: 
1.117     bowersj2 2564: # Unlike the main iterator, this DOES return all resources, even blank ones.
                   2565: #  The main iterator needs them to correctly preprocess the map.
                   2566: 
1.94      bowersj2 2567: sub BEGIN_MAP { return 1; }    # begining of a new map
                   2568: sub END_MAP { return 2; }      # end of the map
                   2569: sub FORWARD { return 1; }      # go forward
                   2570: sub BACKWARD { return 2; }
                   2571: 
1.100     bowersj2 2572: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
                   2573: #         filter hash ref (or undef), already seen hash or undef, condition
                   2574: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
1.51      bowersj2 2575: sub new {
                   2576:     # magic invocation to create a class instance
                   2577:     my $proto = shift;
                   2578:     my $class = ref($proto) || $proto;
                   2579:     my $self = {};
                   2580: 
                   2581:     $self->{NAV_MAP} = shift;
                   2582:     return undef unless ($self->{NAV_MAP});
                   2583: 
                   2584:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
                   2585:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
                   2586: 
                   2587:     # If the given resources are just the ID of the resource, get the
                   2588:     # objects
                   2589:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
                   2590:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
                   2591:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
                   2592:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
                   2593: 
                   2594:     $self->{FILTER} = shift;
                   2595: 
                   2596:     # A hash, used as a set, of resource already seen
                   2597:     $self->{ALREADY_SEEN} = shift;
1.140     bowersj2 2598:      if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1.63      bowersj2 2599:     $self->{CONDITION} = shift;
1.89      bowersj2 2600:     $self->{DIRECTION} = shift || FORWARD();
1.51      bowersj2 2601: 
1.100     bowersj2 2602:     # Flag: Have we started yet?
1.51      bowersj2 2603:     $self->{STARTED} = 0;
                   2604: 
                   2605:     # Should we continue calling the recursive iterator, if any?
                   2606:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2607:     # The recursive iterator, if any
                   2608:     $self->{RECURSIVE_ITERATOR} = undef;
                   2609:     # Are we recursing on a map, or a branch?
                   2610:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
                   2611:     # And the count of how deep it is, so that this iterator can keep track of
                   2612:     # when to pick back up again.
                   2613:     $self->{RECURSIVE_DEPTH} = 0;
                   2614: 
                   2615:     # For keeping track of our branches, we maintain our own stack
1.100     bowersj2 2616:     $self->{STACK} = [];
1.51      bowersj2 2617: 
                   2618:     # Start with the first resource
1.89      bowersj2 2619:     if ($self->{DIRECTION} == FORWARD) {
1.100     bowersj2 2620:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
1.89      bowersj2 2621:     } else {
1.100     bowersj2 2622:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
1.89      bowersj2 2623:     }
1.51      bowersj2 2624: 
                   2625:     bless($self);
                   2626:     return $self;
                   2627: }
                   2628: 
                   2629: sub next {
                   2630:     my $self = shift;
                   2631:     
                   2632:     # Are we using a recursive iterator? If so, pull from that and
                   2633:     # watch the depth; we want to resume our level at the correct time.
1.98      bowersj2 2634:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1.51      bowersj2 2635:         # grab the next from the recursive iterator
                   2636:         my $next = $self->{RECURSIVE_ITERATOR}->next();
                   2637:         
                   2638:         # is it a begin or end map? Update depth if so
                   2639:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
                   2640:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
                   2641: 
                   2642:         # Are we back at depth 0? If so, stop recursing.
                   2643:         if ($self->{RECURSIVE_DEPTH} == 0) {
                   2644:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2645:         }
                   2646:         
                   2647:         return $next;
                   2648:     }
                   2649: 
                   2650:     # Is there a current resource to grab? If not, then return
1.100     bowersj2 2651:     # END_MAP, which will end the iterator.
                   2652:     if (scalar(@{$self->{STACK}}) == 0) {
                   2653:         return $self->END_MAP();
1.51      bowersj2 2654:     }
                   2655: 
                   2656:     # Have we not yet begun? If not, return BEGIN_MAP and 
                   2657:     # remember that we've started.
                   2658:     if ( !$self->{STARTED} ) {
                   2659:         $self->{STARTED} = 1;
                   2660:         return $self->BEGIN_MAP;
                   2661:     }
                   2662: 
                   2663:     # Get the next resource in the branch
1.100     bowersj2 2664:     $self->{HERE} = pop @{$self->{STACK}};
1.52      bowersj2 2665: 
1.100     bowersj2 2666:     # remember that we've seen this, so we don't return it again later
1.51      bowersj2 2667:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
                   2668:     
                   2669:     # Get the next possible resources
1.90      bowersj2 2670:     my $nextUnfiltered;
1.89      bowersj2 2671:     if ($self->{DIRECTION} == FORWARD()) {
1.90      bowersj2 2672:         $nextUnfiltered = $self->{HERE}->getNext();
1.89      bowersj2 2673:     } else {
1.90      bowersj2 2674:         $nextUnfiltered = $self->{HERE}->getPrevious();
1.89      bowersj2 2675:     }
1.51      bowersj2 2676:     my $next = [];
                   2677: 
                   2678:     # filter the next possibilities to remove things we've 
1.100     bowersj2 2679:     # already seen.
1.51      bowersj2 2680:     foreach (@$nextUnfiltered) {
1.52      bowersj2 2681:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
                   2682:             push @$next, $_;
                   2683:         }
1.51      bowersj2 2684:     }
                   2685: 
                   2686:     while (@$next) {
1.100     bowersj2 2687:         # copy the next possibilities over to the stack
                   2688:         push @{$self->{STACK}}, shift @$next;
1.51      bowersj2 2689:     }
                   2690: 
                   2691:     # If this is a map and we want to recurse down it... (not filtered out)
1.70      bowersj2 2692:     if ($self->{HERE}->is_map() && 
1.63      bowersj2 2693:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
1.51      bowersj2 2694:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
                   2695:         my $firstResource = $self->{HERE}->map_start();
                   2696:         my $finishResource = $self->{HERE}->map_finish();
                   2697: 
                   2698:         $self->{RECURSIVE_ITERATOR} =
1.94      bowersj2 2699:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
1.63      bowersj2 2700:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
1.91      bowersj2 2701:                                              $self->{CONDITION}, $self->{DIRECTION});
1.51      bowersj2 2702:     }
                   2703: 
                   2704:     return $self->{HERE};
1.190     bowersj2 2705: }
                   2706: 
                   2707: # Identical to the full iterator methods of the same name. Hate to copy/paste
                   2708: # but I also hate to "inherit" either iterator from the other.
                   2709: 
                   2710: sub getStack {
                   2711:     my $self=shift;
                   2712: 
                   2713:     my @stack;
                   2714: 
                   2715:     $self->populateStack(\@stack);
                   2716: 
                   2717:     return \@stack;
                   2718: }
                   2719: 
                   2720: # Private method: Calls the iterators recursively to populate the stack.
                   2721: sub populateStack {
                   2722:     my $self=shift;
                   2723:     my $stack = shift;
                   2724: 
                   2725:     push @$stack, $self->{HERE} if ($self->{HERE});
                   2726: 
                   2727:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2728:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
                   2729:     }
1.51      bowersj2 2730: }
                   2731: 
1.1       www      2732: 1;
1.2       www      2733: 
1.51      bowersj2 2734: package Apache::lonnavmaps::resource;
                   2735: 
                   2736: use Apache::lonnet;
                   2737: 
                   2738: =pod
                   2739: 
                   2740: =head1 Object: resource
                   2741: 
1.174     albertel 2742: A resource object encapsulates a resource in a resource map, allowing
                   2743: easy manipulation of the resource, querying the properties of the
                   2744: resource (including user properties), and represents a reference that
                   2745: can be used as the canonical representation of the resource by
                   2746: lonnavmap clients like renderers.
                   2747: 
                   2748: A resource only makes sense in the context of a navmap, as some of the
                   2749: data is stored in the navmap object.
                   2750: 
                   2751: You will probably never need to instantiate this object directly. Use
                   2752: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
                   2753: starting resource.
1.51      bowersj2 2754: 
1.188     bowersj2 2755: Resource objects respect the parameter_hiddenparts, which suppresses 
                   2756: various parts according to the wishes of the map author. As of this
                   2757: writing, there is no way to override this parameter, and suppressed
                   2758: parts will never be returned, nor will their response types or ids be
                   2759: stored.
                   2760: 
1.51      bowersj2 2761: =head2 Public Members
                   2762: 
1.174     albertel 2763: resource objects have a hash called DATA ($resourceRef->{DATA}) that
                   2764: you can store whatever you want in. This allows you to easily do
                   2765: two-pass algorithms without worrying about managing your own
                   2766: resource->data hash.
1.51      bowersj2 2767: 
                   2768: =head2 Methods
                   2769: 
                   2770: =over 4
                   2771: 
1.174     albertel 2772: =item * B<new>($navmapRef, $idString):
                   2773: 
                   2774: The first arg is a reference to the parent navmap object. The second
                   2775: is the idString of the resource itself. Very rarely, if ever, called
                   2776: directly. Use the nav map->getByID() method.
1.70      bowersj2 2777: 
                   2778: =back
1.51      bowersj2 2779: 
                   2780: =cut
                   2781: 
                   2782: sub new {
                   2783:     # magic invocation to create a class instance
                   2784:     my $proto = shift;
                   2785:     my $class = ref($proto) || $proto;
                   2786:     my $self = {};
                   2787: 
                   2788:     $self->{NAV_MAP} = shift;
                   2789:     $self->{ID} = shift;
                   2790: 
                   2791:     # Store this new resource in the parent nav map's cache.
                   2792:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
1.66      bowersj2 2793:     $self->{RESOURCE_ERROR} = 0;
1.51      bowersj2 2794: 
                   2795:     # A hash that can be used by two-pass algorithms to store data
                   2796:     # about this resource in. Not used by the resource object
                   2797:     # directly.
                   2798:     $self->{DATA} = {};
                   2799:    
                   2800:     bless($self);
                   2801:     
                   2802:     return $self;
                   2803: }
                   2804: 
1.70      bowersj2 2805: # private function: simplify the NAV_HASH lookups we keep doing
                   2806: # pass the name, and to automatically append my ID, pass a true val on the
                   2807: # second param
                   2808: sub navHash {
                   2809:     my $self = shift;
                   2810:     my $param = shift;
                   2811:     my $id = shift;
1.115     bowersj2 2812:     return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
1.70      bowersj2 2813: }
                   2814: 
1.51      bowersj2 2815: =pod
                   2816: 
1.70      bowersj2 2817: B<Metadata Retreival>
                   2818: 
1.174     albertel 2819: These are methods that help you retrieve metadata about the resource:
                   2820: Method names are based on the fields in the compiled course
                   2821: representation.
1.70      bowersj2 2822: 
                   2823: =over 4
                   2824: 
1.174     albertel 2825: =item * B<compTitle>:
                   2826: 
                   2827: Returns a "composite title", that is equal to $res->title() if the
                   2828: resource has a title, and is otherwise the last part of the URL (e.g.,
                   2829: "problem.problem").
                   2830: 
                   2831: =item * B<ext>:
                   2832: 
                   2833: Returns true if the resource is external.
                   2834: 
                   2835: =item * B<goesto>:
                   2836: 
                   2837: Returns the "goesto" value from the compiled nav map. (It is likely
                   2838: you want to use B<getNext> instead.)
                   2839: 
                   2840: =item * B<kind>:
                   2841: 
                   2842: Returns the kind of the resource from the compiled nav map.
                   2843: 
                   2844: =item * B<randomout>:
1.106     bowersj2 2845: 
1.174     albertel 2846: Returns true if this resource was chosen to NOT be shown to the user
                   2847: by the random map selection feature. In other words, this is usually
                   2848: false.
1.70      bowersj2 2849: 
1.174     albertel 2850: =item * B<randompick>:
1.70      bowersj2 2851: 
1.174     albertel 2852: Returns true for a map if the randompick feature is being used on the
                   2853: map. (?)
1.70      bowersj2 2854: 
1.174     albertel 2855: =item * B<src>:
1.51      bowersj2 2856: 
1.174     albertel 2857: Returns the source for the resource.
1.70      bowersj2 2858: 
1.174     albertel 2859: =item * B<symb>:
1.70      bowersj2 2860: 
1.174     albertel 2861: Returns the symb for the resource.
1.70      bowersj2 2862: 
1.174     albertel 2863: =item * B<title>:
1.70      bowersj2 2864: 
1.174     albertel 2865: Returns the title of the resource.
                   2866: 
                   2867: =item * B<to>:
                   2868: 
                   2869: Returns the "to" value from the compiled nav map. (It is likely you
                   2870: want to use B<getNext> instead.)
1.51      bowersj2 2871: 
                   2872: =back
                   2873: 
                   2874: =cut
                   2875: 
                   2876: # These info functions can be used directly, as they don't return
                   2877: # resource information.
1.85      bowersj2 2878: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
1.70      bowersj2 2879: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
1.85      bowersj2 2880: sub from { my $self=shift; return $self->navHash("from_", 1); }
1.51      bowersj2 2881: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
                   2882: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
1.68      bowersj2 2883: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
                   2884: sub randompick { 
                   2885:     my $self = shift;
                   2886:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
                   2887:                                                '.0.parameter_randompick'};
                   2888: }
1.51      bowersj2 2889: sub src { 
                   2890:     my $self=shift;
                   2891:     return $self->navHash("src_", 1);
                   2892: }
                   2893: sub symb {
                   2894:     my $self=shift;
                   2895:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
                   2896:     my $symbSrc = &Apache::lonnet::declutter($self->src());
                   2897:     return &Apache::lonnet::declutter(
                   2898:          $self->navHash('map_id_'.$first)) 
                   2899:         . '___' . $second . '___' . $symbSrc;
                   2900: }
1.70      bowersj2 2901: sub title { my $self=shift; return $self->navHash("title_", 1); }
                   2902: sub to { my $self=shift; return $self->navHash("to_", 1); }
1.106     bowersj2 2903: sub compTitle {
                   2904:     my $self = shift;
                   2905:     my $title = $self->title();
1.176     www      2906:     $title=~s/\&colon\;/\:/gs;
1.106     bowersj2 2907:     if (!$title) {
                   2908:         $title = $self->src();
                   2909:         $title = substr($title, rindex($title, '/') + 1);
                   2910:     }
                   2911:     return $title;
                   2912: }
1.70      bowersj2 2913: =pod
                   2914: 
                   2915: B<Predicate Testing the Resource>
                   2916: 
                   2917: These methods are shortcuts to deciding if a given resource has a given property.
                   2918: 
                   2919: =over 4
                   2920: 
1.174     albertel 2921: =item * B<is_map>:
                   2922: 
                   2923: Returns true if the resource is a map type.
                   2924: 
                   2925: =item * B<is_problem>:
1.70      bowersj2 2926: 
1.174     albertel 2927: Returns true if the resource is a problem type, false
                   2928: otherwise. (Looks at the extension on the src field; might need more
                   2929: to work correctly.)
1.70      bowersj2 2930: 
1.174     albertel 2931: =item * B<is_page>:
1.70      bowersj2 2932: 
1.174     albertel 2933: Returns true if the resource is a page.
                   2934: 
                   2935: =item * B<is_sequence>:
                   2936: 
                   2937: Returns true if the resource is a sequence.
1.70      bowersj2 2938: 
                   2939: =back
                   2940: 
                   2941: =cut
                   2942: 
                   2943: 
                   2944: sub is_html {
1.51      bowersj2 2945:     my $self=shift;
                   2946:     my $src = $self->src();
1.70      bowersj2 2947:     return ($src =~ /html$/);
1.51      bowersj2 2948: }
1.70      bowersj2 2949: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
                   2950: sub is_page {
1.51      bowersj2 2951:     my $self=shift;
                   2952:     my $src = $self->src();
1.70      bowersj2 2953:     return ($src =~ /page$/);
1.51      bowersj2 2954: }
1.70      bowersj2 2955: sub is_problem {
1.51      bowersj2 2956:     my $self=shift;
                   2957:     my $src = $self->src();
1.70      bowersj2 2958:     return ($src =~ /problem$/);
1.51      bowersj2 2959: }
1.70      bowersj2 2960: sub is_sequence {
1.51      bowersj2 2961:     my $self=shift;
                   2962:     my $src = $self->src();
1.70      bowersj2 2963:     return ($src =~ /sequence$/);
1.51      bowersj2 2964: }
                   2965: 
1.101     bowersj2 2966: # Private method: Shells out to the parmval in the nav map, handler parts.
1.51      bowersj2 2967: sub parmval {
                   2968:     my $self = shift;
                   2969:     my $what = shift;
1.185     bowersj2 2970:     my $part = shift;
                   2971:     if (!defined($part)) { 
                   2972:         $part = '0'; 
                   2973:     }
1.51      bowersj2 2974:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
                   2975: }
                   2976: 
1.70      bowersj2 2977: =pod
                   2978: 
                   2979: B<Map Methods>
                   2980: 
1.174     albertel 2981: These methods are useful for getting information about the map
                   2982: properties of the resource, if the resource is a map (B<is_map>).
1.70      bowersj2 2983: 
                   2984: =over 4
                   2985: 
1.174     albertel 2986: =item * B<map_finish>:
                   2987: 
                   2988: Returns a reference to a resource object corresponding to the finish
                   2989: resource of the map.
1.70      bowersj2 2990: 
1.174     albertel 2991: =item * B<map_pc>:
1.70      bowersj2 2992: 
1.174     albertel 2993: Returns the pc value of the map, which is the first number that
                   2994: appears in the resource ID of the resources in the map, and is the
                   2995: number that appears around the middle of the symbs of the resources in
                   2996: that map.
1.70      bowersj2 2997: 
1.174     albertel 2998: =item * B<map_start>:
                   2999: 
                   3000: Returns a reference to a resource object corresponding to the start
                   3001: resource of the map.
                   3002: 
                   3003: =item * B<map_type>:
                   3004: 
                   3005: Returns a string with the type of the map in it.
1.70      bowersj2 3006: 
                   3007: =back
1.51      bowersj2 3008: 
1.70      bowersj2 3009: =cut
1.51      bowersj2 3010: 
                   3011: sub map_finish {
                   3012:     my $self = shift;
                   3013:     my $src = $self->src();
1.144     bowersj2 3014:     $src = Apache::lonnet::clutter($src);
1.51      bowersj2 3015:     my $res = $self->navHash("map_finish_$src", 0);
                   3016:     $res = $self->{NAV_MAP}->getById($res);
                   3017:     return $res;
                   3018: }
1.70      bowersj2 3019: sub map_pc {
                   3020:     my $self = shift;
                   3021:     my $src = $self->src();
                   3022:     return $self->navHash("map_pc_$src", 0);
                   3023: }
1.51      bowersj2 3024: sub map_start {
                   3025:     my $self = shift;
                   3026:     my $src = $self->src();
1.144     bowersj2 3027:     $src = Apache::lonnet::clutter($src);
1.51      bowersj2 3028:     my $res = $self->navHash("map_start_$src", 0);
                   3029:     $res = $self->{NAV_MAP}->getById($res);
                   3030:     return $res;
                   3031: }
                   3032: sub map_type {
                   3033:     my $self = shift;
                   3034:     my $pc = $self->map_pc();
                   3035:     return $self->navHash("map_type_$pc", 0);
                   3036: }
                   3037: 
                   3038: 
                   3039: 
                   3040: #####
                   3041: # Property queries
                   3042: #####
                   3043: 
                   3044: # These functions will be responsible for returning the CORRECT
                   3045: # VALUE for the parameter, no matter what. So while they may look
                   3046: # like direct calls to parmval, they can be more then that.
                   3047: # So, for instance, the duedate function should use the "duedatetype"
                   3048: # information, rather then the resource object user.
                   3049: 
                   3050: =pod
                   3051: 
                   3052: =head2 Resource Parameters
                   3053: 
1.174     albertel 3054: In order to use the resource parameters correctly, the nav map must
                   3055: have been instantiated with genCourseAndUserOptions set to true, so
                   3056: the courseopt and useropt is read correctly. Then, you can call these
                   3057: functions to get the relevant parameters for the resource. Each
                   3058: function defaults to part "0", but can be directed to another part by
                   3059: passing the part as the parameter.
                   3060: 
                   3061: These methods are responsible for getting the parameter correct, not
                   3062: merely reflecting the contents of the GDBM hashes. As we move towards
                   3063: dates relative to other dates, these methods should be updated to
                   3064: reflect that. (Then, anybody using these methods will not have to update
                   3065: their code.)
                   3066: 
                   3067: =over 4
                   3068: 
                   3069: =item * B<acc>:
                   3070: 
                   3071: Get the Client IP/Name Access Control information.
1.51      bowersj2 3072: 
1.174     albertel 3073: =item * B<answerdate>:
1.51      bowersj2 3074: 
1.174     albertel 3075: Get the answer-reveal date for the problem.
                   3076: 
                   3077: =item * B<duedate>:
                   3078: 
                   3079: Get the due date for the problem.
                   3080: 
                   3081: =item * B<tries>:
                   3082: 
                   3083: Get the number of tries the student has used on the problem.
                   3084: 
                   3085: =item * B<maxtries>:
                   3086: 
                   3087: Get the number of max tries allowed.
                   3088: 
                   3089: =item * B<opendate>:
1.51      bowersj2 3090: 
1.174     albertel 3091: Get the open date for the problem.
1.51      bowersj2 3092: 
1.174     albertel 3093: =item * B<sig>:
1.51      bowersj2 3094: 
1.174     albertel 3095: Get the significant figures setting.
1.51      bowersj2 3096: 
1.174     albertel 3097: =item * B<tol>:
1.51      bowersj2 3098: 
1.174     albertel 3099: Get the tolerance for the problem.
1.51      bowersj2 3100: 
1.174     albertel 3101: =item * B<tries>:
1.51      bowersj2 3102: 
1.174     albertel 3103: Get the number of tries the user has already used on the problem.
1.51      bowersj2 3104: 
1.174     albertel 3105: =item * B<type>:
1.51      bowersj2 3106: 
1.174     albertel 3107: Get the question type for the problem.
1.70      bowersj2 3108: 
1.174     albertel 3109: =item * B<weight>:
1.51      bowersj2 3110: 
1.174     albertel 3111: Get the weight for the problem.
1.51      bowersj2 3112: 
                   3113: =back
                   3114: 
                   3115: =cut
                   3116: 
                   3117: sub acc {
                   3118:     (my $self, my $part) = @_;
                   3119:     return $self->parmval("acc", $part);
                   3120: }
                   3121: sub answerdate {
                   3122:     (my $self, my $part) = @_;
                   3123:     # Handle intervals
                   3124:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
                   3125:         return $self->duedate($part) + 
                   3126:             $self->parmval("answerdate", $part);
                   3127:     }
                   3128:     return $self->parmval("answerdate", $part);
1.106     bowersj2 3129: }
1.108     bowersj2 3130: sub awarded { my $self = shift; return $self->queryRestoreHash('awarded', shift); }
1.51      bowersj2 3131: sub duedate {
                   3132:     (my $self, my $part) = @_;
                   3133:     return $self->parmval("duedate", $part);
                   3134: }
                   3135: sub maxtries {
                   3136:     (my $self, my $part) = @_;
                   3137:     return $self->parmval("maxtries", $part);
                   3138: }
                   3139: sub opendate {
                   3140:     (my $self, my $part) = @_;
                   3141:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
                   3142:         return $self->duedate($part) -
                   3143:             $self->parmval("opendate", $part);
                   3144:     }
                   3145:     return $self->parmval("opendate");
                   3146: }
1.185     bowersj2 3147: sub problemstatus {
                   3148:     (my $self, my $part) = @_;
                   3149:     return $self->parmval("problemstatus", $part);
                   3150: }
1.51      bowersj2 3151: sub sig {
                   3152:     (my $self, my $part) = @_;
                   3153:     return $self->parmval("sig", $part);
                   3154: }
                   3155: sub tol {
                   3156:     (my $self, my $part) = @_;
                   3157:     return $self->parmval("tol", $part);
                   3158: }
1.108     bowersj2 3159: sub tries { 
                   3160:     my $self = shift; 
                   3161:     my $tries = $self->queryRestoreHash('tries', shift);
                   3162:     if (!defined($tries)) { return '0';}
1.51      bowersj2 3163:     return $tries;
                   3164: }
1.70      bowersj2 3165: sub type {
                   3166:     (my $self, my $part) = @_;
                   3167:     return $self->parmval("type", $part);
                   3168: }
1.109     bowersj2 3169: sub weight { 
                   3170:     my $self = shift; my $part = shift;
1.70      bowersj2 3171:     return $self->parmval("weight", $part);
                   3172: }
1.51      bowersj2 3173: 
                   3174: # Multiple things need this
                   3175: sub getReturnHash {
                   3176:     my $self = shift;
                   3177:     
                   3178:     if (!defined($self->{RETURN_HASH})) {
1.84      bowersj2 3179:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
1.51      bowersj2 3180:         $self->{RETURN_HASH} = \%tmpHash;
                   3181:     }
                   3182: }       
                   3183: 
                   3184: ######
                   3185: # Status queries
                   3186: ######
                   3187: 
                   3188: # These methods query the status of problems.
                   3189: 
                   3190: # If we need to count parts, this function determines the number of
                   3191: # parts from the metadata. When called, it returns a reference to a list
                   3192: # of strings corresponding to the parts. (Thus, using it in a scalar context
                   3193: # tells you how many parts you have in the problem:
                   3194: # $partcount = scalar($resource->countParts());
                   3195: # Don't use $self->{PARTS} directly because you don't know if it's been
                   3196: # computed yet.
                   3197: 
                   3198: =pod
                   3199: 
                   3200: =head2 Resource misc
                   3201: 
                   3202: Misc. functions for the resource.
                   3203: 
                   3204: =over 4
                   3205: 
1.174     albertel 3206: =item * B<hasDiscussion>:
1.59      bowersj2 3207: 
1.174     albertel 3208: Returns a false value if there has been discussion since the user last
                   3209: logged in, true if there has. Always returns false if the discussion
                   3210: data was not extracted when the nav map was constructed.
                   3211: 
                   3212: =item * B<getFeedback>:
                   3213: 
                   3214: Gets the feedback for the resource and returns the raw feedback string
                   3215: for the resource, or the null string if there is no feedback or the
                   3216: email data was not extracted when the nav map was constructed. Usually
                   3217: used like this:
1.59      bowersj2 3218: 
                   3219:  for (split(/\,/, $res->getFeedback())) {
                   3220:     my $link = &Apache::lonnet::escape($_);
                   3221:     ...
                   3222: 
                   3223: and use the link as appropriate.
                   3224: 
                   3225: =cut
                   3226: 
                   3227: sub hasDiscussion {
                   3228:     my $self = shift;
                   3229:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
                   3230: }
                   3231: 
                   3232: sub getFeedback {
                   3233:     my $self = shift;
1.124     bowersj2 3234:     my $source = $self->src();
1.125     bowersj2 3235:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
1.124     bowersj2 3236:     return $self->{NAV_MAP}->getFeedback($source);
                   3237: }
                   3238: 
                   3239: sub getErrors {
                   3240:     my $self = shift;
                   3241:     my $source = $self->src();
                   3242:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
                   3243:     return $self->{NAV_MAP}->getErrors($source);
1.59      bowersj2 3244: }
                   3245: 
                   3246: =pod
                   3247: 
1.174     albertel 3248: =item * B<parts>():
1.51      bowersj2 3249: 
1.174     albertel 3250: Returns a list reference containing sorted strings corresponding to
1.193     bowersj2 3251: each part of the problem. Single part problems have only a part '0'.
                   3252: Multipart problems do not return their part '0', since they typically
                   3253: do not really matter. 
1.174     albertel 3254: 
                   3255: =item * B<countParts>():
                   3256: 
                   3257: Returns the number of parts of the problem a student can answer. Thus,
                   3258: for single part problems, returns 1. For multipart, it returns the
1.193     bowersj2 3259: number of parts in the problem, not including psuedo-part 0. 
1.51      bowersj2 3260: 
1.192     bowersj2 3261: =item * B<multipart>():
                   3262: 
1.193     bowersj2 3263: Returns true if the problem is multipart, false otherwise. Use this instead
                   3264: of countParts if all you want is multipart/not multipart.
1.192     bowersj2 3265: 
1.187     bowersj2 3266: =item * B<responseType>($part):
                   3267: 
                   3268: Returns the response type of the part, without the word "response" on the
                   3269: end. Example return values: 'string', 'essay', 'numeric', etc.
                   3270: 
1.193     bowersj2 3271: =item * B<responseIds>($part):
1.187     bowersj2 3272: 
1.193     bowersj2 3273: Retreives the response IDs for the given part as an array reference containing
                   3274: strings naming the response IDs. This may be empty.
1.187     bowersj2 3275: 
1.51      bowersj2 3276: =back
                   3277: 
                   3278: =cut
                   3279: 
                   3280: sub parts {
                   3281:     my $self = shift;
                   3282: 
1.192     bowersj2 3283:     if ($self->ext) { return []; }
1.67      bowersj2 3284: 
1.51      bowersj2 3285:     $self->extractParts();
                   3286:     return $self->{PARTS};
                   3287: }
                   3288: 
                   3289: sub countParts {
                   3290:     my $self = shift;
                   3291:     
                   3292:     my $parts = $self->parts();
1.191     bowersj2 3293: 
                   3294:     # If I left this here, then it's not necessary.
                   3295:     #my $delta = 0;
                   3296:     #for my $part (@$parts) {
                   3297:     #    if ($part eq '0') { $delta--; }
                   3298:     #}
1.66      bowersj2 3299: 
                   3300:     if ($self->{RESOURCE_ERROR}) {
                   3301:         return 0;
                   3302:     }
                   3303: 
1.191     bowersj2 3304:     return scalar(@{$parts}); # + $delta;
1.192     bowersj2 3305: }
                   3306: 
                   3307: sub multipart {
                   3308:     my $self = shift;
                   3309:     return $self->countParts() > 1;
1.51      bowersj2 3310: }
                   3311: 
1.187     bowersj2 3312: sub responseType {
1.184     bowersj2 3313:     my $self = shift;
                   3314:     my $part = shift;
                   3315: 
                   3316:     $self->extractParts();
1.187     bowersj2 3317:     return $self->{RESPONSE_TYPE}->{$part};
                   3318: }
                   3319: 
1.193     bowersj2 3320: sub responseIds {
1.187     bowersj2 3321:     my $self = shift;
                   3322:     my $part = shift;
                   3323: 
                   3324:     $self->extractParts();
                   3325:     return $self->{RESPONSE_IDS}->{$part};
1.184     bowersj2 3326: }
                   3327: 
                   3328: # Private function: Extracts the parts information, both part names and
1.187     bowersj2 3329: # part types, and saves it. 
1.51      bowersj2 3330: sub extractParts { 
                   3331:     my $self = shift;
                   3332:     
1.153     bowersj2 3333:     return if (defined($self->{PARTS}));
1.67      bowersj2 3334:     return if ($self->ext);
1.51      bowersj2 3335: 
                   3336:     $self->{PARTS} = [];
                   3337: 
1.181     bowersj2 3338:     my %parts;
                   3339: 
1.82      bowersj2 3340:     # Retrieve part count, if this is a problem
                   3341:     if ($self->is_problem()) {
1.152     matthew  3342:         my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
1.82      bowersj2 3343:         if (!$metadata) {
                   3344:             $self->{RESOURCE_ERROR} = 1;
                   3345:             $self->{PARTS} = [];
1.184     bowersj2 3346:             $self->{PART_TYPE} = {};
1.82      bowersj2 3347:             return;
                   3348:         }
                   3349:         foreach (split(/\,/,$metadata)) {
1.152     matthew  3350:             if ($_ =~ /^part_(.*)$/) {
1.147     bowersj2 3351:                 my $part = $1;
1.183     bowersj2 3352:                 # This floods the logs if it blows up
                   3353:                 if (defined($parts{$part})) {
                   3354:                     Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->symb());
                   3355:                   }
1.181     bowersj2 3356: 
1.147     bowersj2 3357:                 # check to see if part is turned off.
1.181     bowersj2 3358: 
                   3359:                 if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
                   3360:                     $parts{$part} = 1;
1.147     bowersj2 3361:                 }
1.82      bowersj2 3362:             }
1.51      bowersj2 3363:         }
1.82      bowersj2 3364:         
                   3365:         
1.181     bowersj2 3366:         my @sortedParts = sort keys %parts;
1.82      bowersj2 3367:         $self->{PARTS} = \@sortedParts;
1.187     bowersj2 3368: 
                   3369:         my %responseIdHash;
                   3370:         my %responseTypeHash;
                   3371: 
1.189     bowersj2 3372: 
                   3373:         # Init the responseIdHash
                   3374:         foreach (@{$self->{PARTS}}) {
                   3375:             $responseIdHash{$_} = [];
                   3376:         }
                   3377: 
1.187     bowersj2 3378:         # Now, the unfortunate thing about this is that parts, part name, and
                   3379:         # response if are delimited by underscores, but both the part
                   3380:         # name and response id can themselves have underscores in them.
                   3381:         # So we have to use our knowlege of part names to figure out 
                   3382:         # where the part names begin and end, and even then, it is possible
                   3383:         # to construct ambiguous situations.
                   3384:         foreach (split /,/, $metadata) {
                   3385:             if ($_ =~ /^([a-zA-Z]+)response_(.*)/) {
                   3386:                 my $responseType = $1;
                   3387:                 my $partStuff = $2;
                   3388:                 my $partIdSoFar = '';
                   3389:                 my @partChunks = split /_/, $partStuff;
                   3390:                 my $i = 0;
                   3391: 
                   3392:                 for ($i = 0; $i < scalar(@partChunks); $i++) {
                   3393:                     if ($partIdSoFar) { $partIdSoFar .= '_'; }
                   3394:                     $partIdSoFar .= $partChunks[$i];
                   3395:                     if ($parts{$partIdSoFar}) {
                   3396:                         my @otherChunks = @partChunks[$i+1..$#partChunks];
                   3397:                         my $responseId = join('_', @otherChunks);
1.188     bowersj2 3398:                         push @{$responseIdHash{$partIdSoFar}}, $responseId;
1.187     bowersj2 3399:                         $responseTypeHash{$partIdSoFar} = $responseType;
                   3400:                         last;
                   3401:                     }
                   3402:                 }
                   3403:             }
                   3404:         }
                   3405: 
                   3406:         $self->{RESPONSE_IDS} = \%responseIdHash;
                   3407:         $self->{RESPONSE_TYPES} = \%responseTypeHash;
1.154     bowersj2 3408:     }
                   3409: 
1.51      bowersj2 3410:     return;
                   3411: }
                   3412: 
                   3413: =pod
                   3414: 
                   3415: =head2 Resource Status
                   3416: 
1.174     albertel 3417: Problem resources have status information, reflecting their various
                   3418: dates and completion statuses.
1.51      bowersj2 3419: 
1.174     albertel 3420: There are two aspects to the status: the date-related information and
                   3421: the completion information.
1.51      bowersj2 3422: 
1.174     albertel 3423: Idiomatic usage of these two methods would probably look something
                   3424: like
1.51      bowersj2 3425: 
                   3426:  foreach ($resource->parts()) {
                   3427:     my $dateStatus = $resource->getDateStatus($_);
                   3428:     my $completionStatus = $resource->getCompletionStatus($_);
                   3429: 
1.70      bowersj2 3430:     or
                   3431: 
                   3432:     my $status = $resource->status($_);
                   3433: 
1.51      bowersj2 3434:     ... use it here ...
                   3435:  }
                   3436: 
1.174     albertel 3437: Which you use depends on exactly what you are looking for. The
                   3438: status() function has been optimized for the nav maps display and may
                   3439: not precisely match what you need elsewhere.
1.101     bowersj2 3440: 
1.174     albertel 3441: The symbolic constants shown below can be accessed through the
                   3442: resource object: C<$res->OPEN>.
1.101     bowersj2 3443: 
1.51      bowersj2 3444: =over 4
                   3445: 
1.174     albertel 3446: =item * B<getDateStatus>($part):
                   3447: 
                   3448: ($part defaults to 0). A convenience function that returns a symbolic
                   3449: constant telling you about the date status of the part. The possible
                   3450: return values are:
1.51      bowersj2 3451: 
                   3452: =back
                   3453: 
                   3454: B<Date Codes>
                   3455: 
                   3456: =over 4
                   3457: 
1.174     albertel 3458: =item * B<OPEN_LATER>:
                   3459: 
                   3460: The problem will be opened later.
                   3461: 
                   3462: =item * B<OPEN>:
                   3463: 
                   3464: Open and not yet due.
                   3465: 
1.51      bowersj2 3466: 
1.174     albertel 3467: =item * B<PAST_DUE_ANSWER_LATER>:
1.51      bowersj2 3468: 
1.174     albertel 3469: The due date has passed, but the answer date has not yet arrived.
1.59      bowersj2 3470: 
1.174     albertel 3471: =item * B<PAST_DUE_NO_ANSWER>:
1.54      bowersj2 3472: 
1.174     albertel 3473: The due date has passed and there is no answer opening date set.
1.51      bowersj2 3474: 
1.174     albertel 3475: =item * B<ANSWER_OPEN>:
1.51      bowersj2 3476: 
1.174     albertel 3477: The answer date is here.
                   3478: 
                   3479: =item * B<NETWORK_FAILURE>:
                   3480: 
                   3481: The information is unknown due to network failure.
1.51      bowersj2 3482: 
                   3483: =back
                   3484: 
                   3485: =cut
                   3486: 
                   3487: # Apparently the compiler optimizes these into constants automatically
1.54      bowersj2 3488: sub OPEN_LATER             { return 0; }
                   3489: sub OPEN                   { return 1; }
                   3490: sub PAST_DUE_NO_ANSWER     { return 2; }
                   3491: sub PAST_DUE_ANSWER_LATER  { return 3; }
                   3492: sub ANSWER_OPEN            { return 4; }
                   3493: sub NOTHING_SET            { return 5; } 
                   3494: sub NETWORK_FAILURE        { return 100; }
                   3495: 
                   3496: # getDateStatus gets the date status for a given problem part. 
                   3497: # Because answer date, due date, and open date are fully independent
                   3498: # (i.e., it is perfectly possible to *only* have an answer date), 
                   3499: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
                   3500: # (past, future, none given). This function handles this with a decision
                   3501: # tree. Read the comments to follow the decision tree.
1.51      bowersj2 3502: 
                   3503: sub getDateStatus {
                   3504:     my $self = shift;
                   3505:     my $part = shift;
                   3506:     $part = "0" if (!defined($part));
1.54      bowersj2 3507: 
                   3508:     # Always return network failure if there was one.
1.51      bowersj2 3509:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3510: 
                   3511:     my $now = time();
                   3512: 
1.53      bowersj2 3513:     my $open = $self->opendate($part);
                   3514:     my $due = $self->duedate($part);
                   3515:     my $answer = $self->answerdate($part);
                   3516: 
                   3517:     if (!$open && !$due && !$answer) {
                   3518:         # no data on the problem at all
                   3519:         # should this be the same as "open later"? think multipart.
                   3520:         return $self->NOTHING_SET;
                   3521:     }
1.59      bowersj2 3522:     if (!$open || $now < $open) {return $self->OPEN_LATER}
                   3523:     if (!$due || $now < $due) {return $self->OPEN}
                   3524:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
                   3525:     if ($answer) { return $self->ANSWER_OPEN; }
1.54      bowersj2 3526:     return PAST_DUE_NO_ANSWER;
1.51      bowersj2 3527: }
                   3528: 
                   3529: =pod
                   3530: 
                   3531: B<>
                   3532: 
                   3533: =over 4
                   3534: 
1.174     albertel 3535: =item * B<getCompletionStatus>($part):
1.51      bowersj2 3536: 
1.174     albertel 3537: ($part defaults to 0.) A convenience function that returns a symbolic
                   3538: constant telling you about the completion status of the part, with the
                   3539: following possible results:
                   3540: 
                   3541: =back
1.51      bowersj2 3542: 
                   3543: B<Completion Codes>
                   3544: 
                   3545: =over 4
                   3546: 
1.174     albertel 3547: =item * B<NOT_ATTEMPTED>:
                   3548: 
                   3549: Has not been attempted at all.
                   3550: 
                   3551: =item * B<INCORRECT>:
                   3552: 
                   3553: Attempted, but wrong by student.
1.51      bowersj2 3554: 
1.174     albertel 3555: =item * B<INCORRECT_BY_OVERRIDE>:
1.51      bowersj2 3556: 
1.174     albertel 3557: Attempted, but wrong by instructor override.
1.51      bowersj2 3558: 
1.174     albertel 3559: =item * B<CORRECT>:
1.51      bowersj2 3560: 
1.174     albertel 3561: Correct or correct by instructor.
1.51      bowersj2 3562: 
1.174     albertel 3563: =item * B<CORRECT_BY_OVERRIDE>:
1.51      bowersj2 3564: 
1.174     albertel 3565: Correct by instructor override.
1.51      bowersj2 3566: 
1.174     albertel 3567: =item * B<EXCUSED>:
                   3568: 
                   3569: Excused. Not yet implemented.
                   3570: 
                   3571: =item * B<NETWORK_FAILURE>:
                   3572: 
                   3573: Information not available due to network failure.
                   3574: 
                   3575: =item * B<ATTEMPTED>:
                   3576: 
                   3577: Attempted, and not yet graded.
1.69      bowersj2 3578: 
1.51      bowersj2 3579: =back
                   3580: 
                   3581: =cut
                   3582: 
1.53      bowersj2 3583: sub NOT_ATTEMPTED         { return 10; }
                   3584: sub INCORRECT             { return 11; }
                   3585: sub INCORRECT_BY_OVERRIDE { return 12; }
                   3586: sub CORRECT               { return 13; }
                   3587: sub CORRECT_BY_OVERRIDE   { return 14; }
                   3588: sub EXCUSED               { return 15; }
1.69      bowersj2 3589: sub ATTEMPTED             { return 16; }
1.51      bowersj2 3590: 
                   3591: sub getCompletionStatus {
                   3592:     my $self = shift;
                   3593:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3594: 
1.108     bowersj2 3595:     my $status = $self->queryRestoreHash('solved', shift);
1.51      bowersj2 3596: 
                   3597:     # Left as seperate if statements in case we ever do more with this
                   3598:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
                   3599:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
                   3600:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
                   3601:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
                   3602:     if ($status eq 'excused') {return $self->EXCUSED; }
1.69      bowersj2 3603:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
1.51      bowersj2 3604:     return $self->NOT_ATTEMPTED;
1.108     bowersj2 3605: }
                   3606: 
                   3607: sub queryRestoreHash {
                   3608:     my $self = shift;
                   3609:     my $hashentry = shift;
                   3610:     my $part = shift;
1.185     bowersj2 3611:     $part = "0" if (!defined($part) || $part eq '');
1.108     bowersj2 3612:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3613: 
                   3614:     $self->getReturnHash();
                   3615: 
                   3616:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
1.51      bowersj2 3617: }
                   3618: 
                   3619: =pod
                   3620: 
                   3621: B<Composite Status>
                   3622: 
1.174     albertel 3623: Along with directly returning the date or completion status, the
                   3624: resource object includes a convenience function B<status>() that will
                   3625: combine the two status tidbits into one composite status that can
1.191     bowersj2 3626: represent the status of the resource as a whole. This method represents
                   3627: the concept of the thing we want to display to the user on the nav maps
                   3628: screen, which is a combination of completion and open status. The precise logic is
1.174     albertel 3629: documented in the comments of the status method. The following results
                   3630: may be returned, all available as methods on the resource object
1.185     bowersj2 3631: ($res->NETWORK_FAILURE): In addition to the return values that match
                   3632: the date or completion status, this function can return "ANSWER_SUBMITTED"
                   3633: if that problemstatus parameter value is set to No, suppressing the
                   3634: incorrect/correct feedback.
1.51      bowersj2 3635: 
                   3636: =over 4
                   3637: 
1.174     albertel 3638: =item * B<NETWORK_FAILURE>:
                   3639: 
                   3640: The network has failed and the information is not available.
1.51      bowersj2 3641: 
1.174     albertel 3642: =item * B<NOTHING_SET>:
1.53      bowersj2 3643: 
1.174     albertel 3644: No dates have been set for this problem (part) at all. (Because only
                   3645: certain parts of a multi-part problem may be assigned, this can not be
                   3646: collapsed into "open later", as we do not know a given part will EVER
                   3647: be opened. For single part, this is the same as "OPEN_LATER".)
1.51      bowersj2 3648: 
1.174     albertel 3649: =item * B<CORRECT>:
1.51      bowersj2 3650: 
1.174     albertel 3651: For any reason at all, the part is considered correct.
1.54      bowersj2 3652: 
1.174     albertel 3653: =item * B<EXCUSED>:
1.51      bowersj2 3654: 
1.174     albertel 3655: For any reason at all, the problem is excused.
1.51      bowersj2 3656: 
1.174     albertel 3657: =item * B<PAST_DUE_NO_ANSWER>:
1.51      bowersj2 3658: 
1.174     albertel 3659: The problem is past due, not considered correct, and no answer date is
                   3660: set.
1.51      bowersj2 3661: 
1.174     albertel 3662: =item * B<PAST_DUE_ANSWER_LATER>:
1.51      bowersj2 3663: 
1.174     albertel 3664: The problem is past due, not considered correct, and an answer date in
                   3665: the future is set.
1.51      bowersj2 3666: 
1.174     albertel 3667: =item * B<ANSWER_OPEN>:
                   3668: 
                   3669: The problem is past due, not correct, and the answer is now available.
                   3670: 
                   3671: =item * B<OPEN_LATER>:
                   3672: 
                   3673: The problem is not yet open.
                   3674: 
                   3675: =item * B<TRIES_LEFT>:
                   3676: 
                   3677: The problem is open, has been tried, is not correct, but there are
                   3678: tries left.
                   3679: 
                   3680: =item * B<INCORRECT>:
                   3681: 
                   3682: The problem is open, and all tries have been used without getting the
                   3683: correct answer.
                   3684: 
                   3685: =item * B<OPEN>:
                   3686: 
                   3687: The item is open and not yet tried.
                   3688: 
                   3689: =item * B<ATTEMPTED>:
                   3690: 
                   3691: The problem has been attempted.
1.69      bowersj2 3692: 
1.185     bowersj2 3693: =item * B<ANSWER_SUBMITTED>:
                   3694: 
                   3695: An answer has been submitted, but the student should not see it.
                   3696: 
1.51      bowersj2 3697: =back
                   3698: 
                   3699: =cut
                   3700: 
1.185     bowersj2 3701: sub TRIES_LEFT       { return 20; }
                   3702: sub ANSWER_SUBMITTED { return 21; }
1.51      bowersj2 3703: 
                   3704: sub status {
                   3705:     my $self = shift;
                   3706:     my $part = shift;
                   3707:     if (!defined($part)) { $part = "0"; }
                   3708:     my $completionStatus = $self->getCompletionStatus($part);
                   3709:     my $dateStatus = $self->getDateStatus($part);
                   3710: 
                   3711:     # What we have is a two-dimensional matrix with 4 entries on one
                   3712:     # dimension and 5 entries on the other, which we want to colorize,
1.54      bowersj2 3713:     # plus network failure and "no date data at all".
1.51      bowersj2 3714: 
1.53      bowersj2 3715:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
1.51      bowersj2 3716: 
1.186     bowersj2 3717:     my $suppressFeedback = lc($self->parmval("problemstatus", $part)) eq 'no';
1.185     bowersj2 3718: 
1.51      bowersj2 3719:     # There are a few whole rows we can dispose of:
1.53      bowersj2 3720:     if ($completionStatus == CORRECT ||
                   3721:         $completionStatus == CORRECT_BY_OVERRIDE ) {
1.185     bowersj2 3722:         return $suppressFeedback? ANSWER_SUBMITTED : CORRECT; 
1.69      bowersj2 3723:     }
                   3724: 
                   3725:     if ($completionStatus == ATTEMPTED) {
                   3726:         return ATTEMPTED;
1.53      bowersj2 3727:     }
                   3728: 
                   3729:     # If it's EXCUSED, then return that no matter what
                   3730:     if ($completionStatus == EXCUSED) {
                   3731:         return EXCUSED; 
1.51      bowersj2 3732:     }
                   3733: 
1.53      bowersj2 3734:     if ($dateStatus == NOTHING_SET) {
                   3735:         return NOTHING_SET;
1.51      bowersj2 3736:     }
                   3737: 
1.69      bowersj2 3738:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
                   3739:     # by 4 matrix (date statuses).
1.51      bowersj2 3740: 
1.54      bowersj2 3741:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
1.59      bowersj2 3742:         $dateStatus == PAST_DUE_NO_ANSWER ) {
1.54      bowersj2 3743:         return $dateStatus; 
1.51      bowersj2 3744:     }
                   3745: 
1.53      bowersj2 3746:     if ($dateStatus == ANSWER_OPEN) {
                   3747:         return ANSWER_OPEN;
1.51      bowersj2 3748:     }
                   3749: 
                   3750:     # Now: (incorrect, incorrect_override, not_attempted) x 
                   3751:     # (open_later), (open)
                   3752:     
1.53      bowersj2 3753:     if ($dateStatus == OPEN_LATER) {
                   3754:         return OPEN_LATER;
1.51      bowersj2 3755:     }
                   3756: 
                   3757:     # If it's WRONG...
1.53      bowersj2 3758:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
1.51      bowersj2 3759:         # and there are TRIES LEFT:
1.79      bowersj2 3760:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
1.53      bowersj2 3761:             return TRIES_LEFT;
1.51      bowersj2 3762:         }
1.185     bowersj2 3763:         return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
1.51      bowersj2 3764:     }
                   3765: 
                   3766:     # Otherwise, it's untried and open
1.53      bowersj2 3767:     return OPEN; 
1.191     bowersj2 3768: }
                   3769: 
                   3770: =pod
                   3771: 
                   3772: B<Completable>
                   3773: 
                   3774: The completable method represents the concept of I<whether the student can
                   3775: currently do the problem>. If the student can do the problem, which means
                   3776: that it is open, there are tries left, and if the problem is manually graded
                   3777: or the grade is suppressed via problemstatus, the student has not tried it
                   3778: yet, then the method returns 1. Otherwise, it returns 0, to indicate that 
                   3779: either the student has tried it and there is no feedback, or that for
                   3780: some reason it is no longer completable (not open yet, successfully completed,
                   3781: out of tries, etc.). As an example, this is used as the filter for the
                   3782: "Uncompleted Homework" option for the nav maps.
                   3783: 
                   3784: If this does not quite meet your needs, do not fiddle with it (unless you are
                   3785: fixing it to better match the student's conception of "completable" because
                   3786: it's broken somehow)... make a new method.
                   3787: 
                   3788: =cut
                   3789: 
                   3790: sub completable {
                   3791:     my $self = shift;
                   3792:     if (!$self->is_problem()) { return 0; }
                   3793:     my $partCount = $self->countParts();
                   3794: 
                   3795:     foreach my $part (@{$self->parts()}) {
                   3796:         if ($part eq '0' && $partCount != 1) { next; }
                   3797:         my $status = $self->status($part);
                   3798:         # "If any of the parts are open, or have tries left (implies open),
                   3799:         # and it is not "attempted" (manually graded problem), it is
                   3800:         # not "complete"
                   3801:         if (!(($status == OPEN() || $status == TRIES_LEFT()) 
                   3802:               && $self->getCompletionStatus($part) != ATTEMPTED()
                   3803:               && $status != ANSWER_SUBMITTED())) {
                   3804:             return 0;
                   3805:         }
                   3806:     }
                   3807:         
                   3808:     # If all the parts were complete, so was this problem.
                   3809:     return 1;
1.51      bowersj2 3810: }
                   3811: 
                   3812: =pod
                   3813: 
                   3814: =head2 Resource/Nav Map Navigation
                   3815: 
                   3816: =over 4
                   3817: 
1.174     albertel 3818: =item * B<getNext>():
                   3819: 
                   3820: Retreive an array of the possible next resources after this
                   3821: one. Always returns an array, even in the one- or zero-element case.
                   3822: 
                   3823: =item * B<getPrevious>():
1.85      bowersj2 3824: 
1.174     albertel 3825: Retreive an array of the possible previous resources from this
                   3826: one. Always returns an array, even in the one- or zero-element case.
1.51      bowersj2 3827: 
                   3828: =cut
                   3829: 
                   3830: sub getNext {
                   3831:     my $self = shift;
                   3832:     my @branches;
                   3833:     my $to = $self->to();
1.85      bowersj2 3834:     foreach my $branch ( split(/,/, $to) ) {
1.51      bowersj2 3835:         my $choice = $self->{NAV_MAP}->getById($branch);
                   3836:         my $next = $choice->goesto();
                   3837:         $next = $self->{NAV_MAP}->getById($next);
                   3838: 
1.131     bowersj2 3839:         push @branches, $next;
1.85      bowersj2 3840:     }
                   3841:     return \@branches;
                   3842: }
                   3843: 
                   3844: sub getPrevious {
                   3845:     my $self = shift;
                   3846:     my @branches;
                   3847:     my $from = $self->from();
                   3848:     foreach my $branch ( split /,/, $from) {
                   3849:         my $choice = $self->{NAV_MAP}->getById($branch);
                   3850:         my $prev = $choice->comesfrom();
                   3851:         $prev = $self->{NAV_MAP}->getById($prev);
                   3852: 
1.131     bowersj2 3853:         push @branches, $prev;
1.51      bowersj2 3854:     }
                   3855:     return \@branches;
1.131     bowersj2 3856: }
                   3857: 
                   3858: sub browsePriv {
                   3859:     my $self = shift;
                   3860:     if (defined($self->{BROWSE_PRIV})) {
                   3861:         return $self->{BROWSE_PRIV};
                   3862:     }
                   3863: 
                   3864:     $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
1.51      bowersj2 3865: }
                   3866: 
                   3867: =pod
1.2       www      3868: 
1.51      bowersj2 3869: =back
1.2       www      3870: 
1.51      bowersj2 3871: =cut
1.2       www      3872: 
1.51      bowersj2 3873: 1;
1.2       www      3874: 
1.51      bowersj2 3875: __END__
1.2       www      3876: 
                   3877: 

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