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

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

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