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

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

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