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

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

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