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

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

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