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

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

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