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

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

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