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

1.2       www         1: # The LearningOnline Network with CAPA
                      2: # Navigate Maps Handler
1.1       www         3: #
1.255   ! albertel    4: # $Id: lonnavmaps.pm,v 1.254 2004/03/17 16:28:23 matthew 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.251     www       317: # Convenience function: This separates the logic of how to create
1.53      bowersj2  318: # the problem text strings ("Due: DATE", "Open: DATE", "Not yet assigned",
1.251     www       319: # etc.) into a separate function. It takes a resource object as the
1.53      bowersj2  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: 
1.252     matthew   384: sub dueInLessThan24Hours {
1.115     bowersj2  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();
1.254     matthew  1014:         my $errorcount = 0;
1.134     bowersj2 1015:         foreach (split(/,/, $errors)) {
1.254     matthew  1016:             last if ($errorcount>=10); # Only output 10 bombs maximum
1.134     bowersj2 1017:             if ($_) {
1.254     matthew  1018:                 $errorcount++;
1.134     bowersj2 1019:                 $errorHTML .= '&nbsp;<a href="/adm/email?display='
                   1020:                     . &Apache::lonnet::escape($_) . '">'
                   1021:                     . '<img src="/adm/lonMisc/bomb.gif" '
                   1022:                     . 'border="0" /></a>';
                   1023:             }
                   1024:         }
1.197     bowersj2 1025:     }
                   1026: 
                   1027:     if ($params->{'multipart'} && $part != '0') {
                   1028: 	$discussionHTML = $feedbackHTML = $errorHTML = '';
1.134     bowersj2 1029:     }
                   1030: 
                   1031:     return "<td width=\"75\" align=\"left\" valign=\"center\">$discussionHTML$feedbackHTML$errorHTML&nbsp;</td>";
                   1032: 
1.133     bowersj2 1033: }
                   1034: sub render_quick_status {
                   1035:     my ($resource, $part, $params) = @_;
1.135     bowersj2 1036:     my $result = "";
                   1037:     my $firstDisplayed = !$params->{'condensed'} && 
                   1038:         $params->{'multipart'} && $part eq "0";
                   1039: 
                   1040:     my $link = $params->{"resourceLink"};
                   1041:     my $linkopen = "<a href='$link'>";
                   1042:     my $linkclose = "</a>";
                   1043: 
                   1044:     if ($resource->is_problem() &&
                   1045:         !$firstDisplayed) {
1.224     bowersj2 1046: 	
                   1047:         my $icon = $statusIconMap{$resource->simpleStatus($part)};
1.135     bowersj2 1048:         my $alt = $iconAltTags{$icon};
                   1049:         if ($icon) {
                   1050:             $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";
                   1051:         } else {
                   1052:             $result .= "<td width='30'>&nbsp;</td>\n";
                   1053:         }
                   1054:     } else { # not problem, no icon
                   1055:         $result .= "<td width='30'>&nbsp;</td>\n";
                   1056:     }
                   1057: 
                   1058:     return $result;
1.133     bowersj2 1059: }
                   1060: sub render_long_status {
                   1061:     my ($resource, $part, $params) = @_;
1.136     bowersj2 1062:     my $result = "<td align='right' valign='center'>\n";
                   1063:     my $firstDisplayed = !$params->{'condensed'} && 
                   1064:         $params->{'multipart'} && $part eq "0";
                   1065:                 
                   1066:     my $color;
1.212     bowersj2 1067:     if ($resource->is_problem()) {
1.136     bowersj2 1068:         $color = $colormap{$resource->status};
                   1069:         
1.252     matthew  1070:         if (dueInLessThan24Hours($resource, $part) ||
1.136     bowersj2 1071:             lastTry($resource, $part)) {
                   1072:             $color = $hurryUpColor;
                   1073:         }
                   1074:     }
                   1075:     
                   1076:     if ($resource->kind() eq "res" &&
                   1077:         $resource->is_problem() &&
                   1078:         !$firstDisplayed) {
                   1079:         if ($color) {$result .= "<font color=\"$color\"><b>"; }
                   1080:         $result .= getDescription($resource, $part);
                   1081:         if ($color) {$result .= "</b></font>"; }
                   1082:     }
                   1083:     if ($resource->is_map() && advancedUser() && $resource->randompick()) {
                   1084:         $result .= '(randomly select ' . $resource->randompick() .')';
                   1085:     }
1.210     bowersj2 1086: 
1.213     bowersj2 1087:     # Debugging code
                   1088:     #$result .= " " . $resource->awarded($part) . '/' . $resource->weight($part) .
                   1089:     #	' - Part: ' . $part;
                   1090: 
1.210     bowersj2 1091:     $result .= "</td>\n";
1.136     bowersj2 1092:     
                   1093:     return $result;
1.51      bowersj2 1094: }
                   1095: 
1.227     bowersj2 1096: # Colors obtained by taking the icons, matching the colors, and
                   1097: # possibly reducing the Value (HSV) of the color, if it's too bright
                   1098: # for text, generally by one third or so.
1.225     bowersj2 1099: my %statusColors = 
                   1100:     (
                   1101:      $resObj->CLOSED => '#000000',
1.227     bowersj2 1102:      $resObj->OPEN   => '#998b13',
                   1103:      $resObj->CORRECT => '#26933f',
                   1104:      $resObj->INCORRECT => '#c48207',
                   1105:      $resObj->ATTEMPTED => '#a87510',
1.225     bowersj2 1106:      $resObj->ERROR => '#000000'
                   1107:      );
                   1108: my %statusStrings = 
                   1109:     (
                   1110:      $resObj->CLOSED => 'Not yet open',
                   1111:      $resObj->OPEN   => 'Open',
                   1112:      $resObj->CORRECT => 'Correct',
                   1113:      $resObj->INCORRECT => 'Incorrect',
                   1114:      $resObj->ATTEMPTED => 'Attempted',
                   1115:      $resObj->ERROR => 'Network Error'
                   1116:      );
                   1117: my @statuses = ($resObj->CORRECT, $resObj->ATTEMPTED, $resObj->INCORRECT, $resObj->OPEN, $resObj->CLOSED, $resObj->ERROR);
                   1118: 
                   1119: use Data::Dumper;
                   1120: sub render_parts_summary_status {
                   1121:     my ($resource, $part, $params) = @_;
                   1122:     if (!$resource->is_problem()) { return '<td></td>'; }
                   1123:     if ($params->{showParts}) { 
                   1124: 	return '<td></td>';
                   1125:     }
                   1126: 
                   1127:     my $td = "<td align='right'>\n";
                   1128:     my $endtd = "</td>\n";
                   1129: 
                   1130:     # If there is a single part, just show the simple status
                   1131:     if ($resource->singlepart()) {
1.253     albertel 1132: 	my $status = $resource->simpleStatus(${$resource->parts}[0]);
1.225     bowersj2 1133: 	return $td . "<font color='" . $statusColors{$status} . "'>"
                   1134: 	    . $statusStrings{$status} . "</font>" . $endtd;
                   1135:     }
                   1136: 
                   1137:     # Now we can be sure the $part doesn't really matter.
                   1138:     my $statusCount = $resource->simpleStatusCount();
                   1139:     my @counts;
                   1140:     foreach my $status(@statuses) {
                   1141: 	# decouple display order from the simpleStatusCount order
                   1142: 	my $slot = Apache::lonnavmaps::resource::statusToSlot($status);
                   1143: 	if ($statusCount->[$slot]) {
                   1144: 	    push @counts, "<font color='" . $statusColors{$status} .
                   1145: 		"'>" . $statusCount->[$slot] . ' '
                   1146: 		. $statusStrings{$status} . "</font>";
                   1147: 	}
                   1148:     }
                   1149: 
1.227     bowersj2 1150:     return $td . $resource->countParts() . ' parts: ' . join (', ', @counts) . $endtd;
1.225     bowersj2 1151: }
                   1152: 
1.133     bowersj2 1153: my @preparedColumns = (\&render_resource, \&render_communication_status,
1.225     bowersj2 1154:                        \&render_quick_status, \&render_long_status,
                   1155: 		       \&render_parts_summary_status);
1.132     bowersj2 1156: 
                   1157: sub setDefault {
                   1158:     my ($val, $default) = @_;
                   1159:     if (!defined($val)) { return $default; }
                   1160:     return $val;
                   1161: }
                   1162: 
                   1163: sub render {
                   1164:     my $args = shift;
1.140     bowersj2 1165:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
                   1166:     my $result = '';
                   1167: 
1.132     bowersj2 1168:     # Configure the renderer.
                   1169:     my $cols = $args->{'cols'};
                   1170:     if (!defined($cols)) {
                   1171:         # no columns, no nav maps.
                   1172:         return '';
                   1173:     }
1.140     bowersj2 1174:     my $mustCloseNavMap = 0;
                   1175:     my $navmap;
                   1176:     if (defined($args->{'navmap'})) {
                   1177:         $navmap = $args->{'navmap'};
                   1178:     }
                   1179: 
1.158     bowersj2 1180:     my $r = $args->{'r'};
1.140     bowersj2 1181:     my $queryString = $args->{'queryString'};
1.159     bowersj2 1182:     my $jump = $args->{'jump'};
1.158     bowersj2 1183:     my $here = $args->{'here'};
1.153     bowersj2 1184:     my $suppressNavmap = setDefault($args->{'suppressNavmap'}, 0);
1.140     bowersj2 1185:     my $currentJumpDelta = 2; # change this to change how many resources are displayed
                   1186:                              # before the current resource when using #current
                   1187: 
                   1188:     # If we were passed 'here' information, we are not rendering
                   1189:     # after a folder manipulation, and we were not passed an
                   1190:     # iterator, make sure we open the folders to show the "here"
                   1191:     # marker
                   1192:     my $filterHash = {};
                   1193:     # Figure out what we're not displaying
                   1194:     foreach (split(/\,/, $ENV{"form.filter"})) {
                   1195:         if ($_) {
                   1196:             $filterHash->{$_} = "1";
                   1197:         }
                   1198:     }
                   1199: 
1.191     bowersj2 1200:     # Filter: Remember filter function and add our own filter: Refuse
                   1201:     # to show hidden resources unless the user can see them.
                   1202:     my $userCanSeeHidden = advancedUser();
                   1203:     my $filterFunc = setDefault($args->{'filterFunc'},
                   1204:                                 sub {return 1;});
                   1205:     if (!$userCanSeeHidden) {
                   1206:         # Without renaming the filterfunc, the server seems to go into
                   1207:         # an infinite loop
                   1208:         my $oldFilterFunc = $filterFunc;
                   1209:         $filterFunc = sub { my $res = shift; return !$res->randomout() && 
                   1210:                                 &$oldFilterFunc($res);};
                   1211:     }
                   1212: 
1.140     bowersj2 1213:     my $condition = 0;
                   1214:     if ($ENV{'form.condition'}) {
                   1215:         $condition = 1;
                   1216:     }
                   1217: 
                   1218:     if (!$ENV{'form.folderManip'} && !defined($args->{'iterator'})) {
                   1219:         # Step 1: Check to see if we have a navmap
                   1220:         if (!defined($navmap)) {
1.221     bowersj2 1221:             $navmap = Apache::lonnavmaps::navmap->new();
1.140     bowersj2 1222:             $mustCloseNavMap = 1;
                   1223:         }
                   1224: 
                   1225:         # Step two: Locate what kind of here marker is necessary
                   1226:         # Determine where the "here" marker is and where the screen jumps to.
                   1227: 
1.175     bowersj2 1228:         if ($ENV{'form.postsymb'}) {
                   1229:             $here = $jump = $ENV{'form.postsymb'};
1.140     bowersj2 1230:         } elsif ($ENV{'form.postdata'}) {
                   1231:             # couldn't find a symb, is there a URL?
                   1232:             my $currenturl = $ENV{'form.postdata'};
1.158     bowersj2 1233:             #$currenturl=~s/^http\:\/\///;
                   1234:             #$currenturl=~s/^[^\/]+//;
1.140     bowersj2 1235:             
1.158     bowersj2 1236:             $here = $jump = &Apache::lonnet::symbread($currenturl);
1.140     bowersj2 1237:         }
1.158     bowersj2 1238: 
1.140     bowersj2 1239:         # Step three: Ensure the folders are open
                   1240:         my $mapIterator = $navmap->getIterator(undef, undef, undef, 1);
1.222     bowersj2 1241:         my $curRes;
1.140     bowersj2 1242:         my $found = 0;
                   1243:         
                   1244:         # We only need to do this if we need to open the maps to show the
                   1245:         # current position. This will change the counter so we can't count
                   1246:         # for the jump marker with this loop.
1.222     bowersj2 1247:         while (($curRes = $mapIterator->next()) && !$found) {
1.158     bowersj2 1248:             if (ref($curRes) && $curRes->symb() eq $here) {
1.140     bowersj2 1249:                 my $mapStack = $mapIterator->getStack();
                   1250:                 
                   1251:                 # Ensure the parent maps are open
                   1252:                 for my $map (@{$mapStack}) {
                   1253:                     if ($condition) {
                   1254:                         undef $filterHash->{$map->map_pc()};
                   1255:                     } else {
                   1256:                         $filterHash->{$map->map_pc()} = 1;
                   1257:                     }
                   1258:                 }
                   1259:                 $found = 1;
                   1260:             }
                   1261:         }            
1.159     bowersj2 1262:     }        
1.140     bowersj2 1263: 
                   1264:     if ( !defined($args->{'iterator'}) && $ENV{'form.folderManip'} ) { # we came from a user's manipulation of the nav page
                   1265:         # If this is a click on a folder or something, we want to preserve the "here"
                   1266:         # from the querystring, and get the new "jump" marker
                   1267:         $here = $ENV{'form.here'};
                   1268:         $jump = $ENV{'form.jump'};
                   1269:     } 
                   1270:     
1.132     bowersj2 1271:     my $it = $args->{'iterator'};
                   1272:     if (!defined($it)) {
1.140     bowersj2 1273:         # Construct a default iterator based on $ENV{'form.'} information
                   1274:         
                   1275:         # Step 1: Check to see if we have a navmap
                   1276:         if (!defined($navmap)) {
1.221     bowersj2 1277:             $navmap = Apache::lonnavmaps::navmap->new();
1.140     bowersj2 1278:             $mustCloseNavMap = 1;
                   1279:         }
                   1280: 
1.144     bowersj2 1281:         # See if we're being passed a specific map
                   1282:         if ($args->{'iterator_map'}) {
                   1283:             my $map = $args->{'iterator_map'};
1.145     bowersj2 1284:             $map = $navmap->getResourceByUrl($map);
1.144     bowersj2 1285:             my $firstResource = $map->map_start();
                   1286:             my $finishResource = $map->map_finish();
                   1287: 
                   1288:             $args->{'iterator'} = $it = $navmap->getIterator($firstResource, $finishResource, $filterHash, $condition);
                   1289:         } else {
                   1290:             $args->{'iterator'} = $it = $navmap->getIterator(undef, undef, $filterHash, $condition);
                   1291:         }
1.132     bowersj2 1292:     }
                   1293:     
1.159     bowersj2 1294:     # (re-)Locate the jump point, if any
1.191     bowersj2 1295:     # Note this does not take filtering or hidden into account... need
                   1296:     # to be fixed?
1.159     bowersj2 1297:     my $mapIterator = $navmap->getIterator(undef, undef, $filterHash, 0);
1.222     bowersj2 1298:     my $curRes;
1.159     bowersj2 1299:     my $foundJump = 0;
                   1300:     my $counter = 0;
                   1301:     
1.222     bowersj2 1302:     while (($curRes = $mapIterator->next()) && !$foundJump) {
1.159     bowersj2 1303:         if (ref($curRes)) { $counter++; }
                   1304:         
                   1305:         if (ref($curRes) && $jump eq $curRes->symb()) {
                   1306:             
                   1307:             # This is why we have to use the main iterator instead of the
                   1308:             # potentially faster DFS: The count has to be the same, so
                   1309:             # the order has to be the same, which DFS won't give us.
                   1310:             $args->{'currentJumpIndex'} = $counter;
                   1311:             $foundJump = 1;
                   1312:         }
                   1313:     }
                   1314: 
1.132     bowersj2 1315:     my $showParts = setDefault($args->{'showParts'}, 1);
                   1316:     my $condenseParts = setDefault($args->{'condenseParts'}, 1);
1.139     bowersj2 1317:     # keeps track of when the current resource is found,
                   1318:     # so we can back up a few and put the anchor above the
                   1319:     # current resource
1.140     bowersj2 1320:     my $printKey = $args->{'printKey'};
                   1321:     my $printCloseAll = $args->{'printCloseAll'};
                   1322:     if (!defined($printCloseAll)) { $printCloseAll = 1; }
1.144     bowersj2 1323:     
1.140     bowersj2 1324:     # Print key?
                   1325:     if ($printKey) {
                   1326:         $result .= '<table border="0" cellpadding="2" cellspacing="0">';
                   1327:         my $date=localtime;
                   1328:         $result.='<tr><td align="right" valign="bottom">Key:&nbsp;&nbsp;</td>';
                   1329:         if ($navmap->{LAST_CHECK}) {
                   1330:             $result .= 
1.230     www      1331:                 '<img src="/adm/lonMisc/chat.gif"> '.&mt('New discussion since').' '.
1.140     bowersj2 1332:                 strftime("%A, %b %e at %I:%M %P", localtime($navmap->{LAST_CHECK})).
                   1333:                 '</td><td align="center" valign="bottom">&nbsp;&nbsp;'.
1.230     www      1334:                 '<img src="/adm/lonMisc/feedback.gif"> '.&mt('New message (click to open)').'<p>'.
1.140     bowersj2 1335:                 '</td>'; 
                   1336:         } else {
                   1337:             $result .= '<td align="center" valign="bottom">&nbsp;&nbsp;'.
1.230     www      1338:                 '<img src="/adm/lonMisc/chat.gif"> '.&mt('Discussions').'</td><td align="center" valign="bottom">'.
                   1339:                 '&nbsp;&nbsp;<img src="/adm/lonMisc/feedback.gif"> '.&mt('New message (click to open)').
1.140     bowersj2 1340:                 '</td>'; 
                   1341:         }
                   1342: 
                   1343:         $result .= '</tr></table>';
                   1344:     }
                   1345: 
1.172     bowersj2 1346:     if ($printCloseAll && !$args->{'resource_no_folder_link'}) {
1.140     bowersj2 1347:         if ($condition) {
                   1348:             $result.="<a href=\"navmaps?condition=0&filter=&$queryString" .
1.158     bowersj2 1349:                 "&here=" . Apache::lonnet::escape($here) .
1.230     www      1350:                 "\">".&mt('Close All Folders')."</a>";
1.140     bowersj2 1351:         } else {
                   1352:             $result.="<a href=\"navmaps?condition=1&filter=&$queryString" .
1.158     bowersj2 1353:                 "&here=" . Apache::lonnet::escape($here) . 
1.230     www      1354:                 "\">".&mt('Open All Folders')."</a>";
1.140     bowersj2 1355:         }
1.143     bowersj2 1356:         $result .= "<br /><br />\n";
1.140     bowersj2 1357:     }    
                   1358: 
                   1359:     if ($r) {
                   1360:         $r->print($result);
                   1361:         $r->rflush();
                   1362:         $result = "";
                   1363:     }
1.132     bowersj2 1364:     # End parameter setting
1.133     bowersj2 1365:             
1.132     bowersj2 1366:     # Data
1.140     bowersj2 1367:     $result .= '<table cellspacing="0" cellpadding="3" border="0" bgcolor="#FFFFFF">' ."\n";
1.132     bowersj2 1368:     my $res = "Apache::lonnavmaps::resource";
                   1369:     my %condenseStatuses =
                   1370:         ( $res->NETWORK_FAILURE    => 1,
                   1371:           $res->NOTHING_SET        => 1,
                   1372:           $res->CORRECT            => 1 );
                   1373:     my @backgroundColors = ("#FFFFFF", "#F6F6F6");
1.133     bowersj2 1374: 
                   1375:     # Shared variables
                   1376:     $args->{'counter'} = 0; # counts the rows
                   1377:     $args->{'indentLevel'} = 0;
                   1378:     $args->{'isNewBranch'} = 0;
                   1379:     $args->{'condensed'} = 0;    
                   1380:     $args->{'indentString'} = setDefault($args->{'indentString'}, "<img src='/adm/lonIcons/whitespace1.gif' width='25' height='1' alt='' border='0' />");
                   1381:     $args->{'displayedHereMarker'} = 0;
1.132     bowersj2 1382: 
1.190     bowersj2 1383:     # If we're suppressing empty sequences, look for them here. Use DFS for speed,
                   1384:     # since structure actually doesn't matter, except what map has what resources.
                   1385:     if ($args->{'suppressEmptySequences'}) {
                   1386:         my $dfsit = Apache::lonnavmaps::DFSiterator->new($navmap,
                   1387:                                                          $it->{FIRST_RESOURCE},
                   1388:                                                          $it->{FINISH_RESOURCE},
                   1389:                                                          {}, undef, 1);
1.222     bowersj2 1390:         my $depth = 0;
1.190     bowersj2 1391:         $dfsit->next();
                   1392:         my $curRes = $dfsit->next();
                   1393:         while ($depth > -1) {
                   1394:             if ($curRes == $dfsit->BEGIN_MAP()) { $depth++; }
                   1395:             if ($curRes == $dfsit->END_MAP()) { $depth--; }
                   1396: 
                   1397:             if (ref($curRes)) { 
                   1398:                 # Parallel pre-processing: Do sequences have non-filtered-out children?
1.201     bowersj2 1399:                 if ($curRes->is_map()) {
1.190     bowersj2 1400:                     $curRes->{DATA}->{HAS_VISIBLE_CHILDREN} = 0;
                   1401:                     # Sequences themselves do not count as visible children,
                   1402:                     # unless those sequences also have visible children.
                   1403:                     # This means if a sequence appears, there's a "promise"
                   1404:                     # that there's something under it if you open it, somewhere.
                   1405:                 } else {
                   1406:                     # Not a sequence: if it's filtered, ignore it, otherwise
                   1407:                     # rise up the stack and mark the sequences as having children
                   1408:                     if (&$filterFunc($curRes)) {
                   1409:                         for my $sequence (@{$dfsit->getStack()}) {
                   1410:                             $sequence->{DATA}->{HAS_VISIBLE_CHILDREN} = 1;
                   1411:                         }
                   1412:                     }
                   1413:                 }
                   1414:             }
                   1415:         } continue {
                   1416:             $curRes = $dfsit->next();
                   1417:         }
                   1418:     }
                   1419: 
1.133     bowersj2 1420:     my $displayedJumpMarker = 0;
1.132     bowersj2 1421:     # Set up iteration.
                   1422:     my $now = time();
                   1423:     my $in24Hours = $now + 24 * 60 * 60;
                   1424:     my $rownum = 0;
                   1425: 
1.141     bowersj2 1426:     # export "here" marker information
                   1427:     $args->{'here'} = $here;
                   1428: 
1.222     bowersj2 1429:     $args->{'indentLevel'} = -1; # first BEGIN_MAP takes this to 0
                   1430:     while ($curRes = $it->next()) {
1.132     bowersj2 1431:         # Maintain indentation level.
                   1432:         if ($curRes == $it->BEGIN_MAP() ||
                   1433:             $curRes == $it->BEGIN_BRANCH() ) {
1.133     bowersj2 1434:             $args->{'indentLevel'}++;
1.132     bowersj2 1435:         }
                   1436:         if ($curRes == $it->END_MAP() ||
                   1437:             $curRes == $it->END_BRANCH() ) {
1.133     bowersj2 1438:             $args->{'indentLevel'}--;
1.132     bowersj2 1439:         }
                   1440:         # Notice new branches
                   1441:         if ($curRes == $it->BEGIN_BRANCH()) {
1.133     bowersj2 1442:             $args->{'isNewBranch'} = 1;
                   1443:         }
                   1444: 
                   1445:         # If this isn't an actual resource, continue on
                   1446:         if (!ref($curRes)) {
                   1447:             next;
1.132     bowersj2 1448:         }
1.133     bowersj2 1449: 
1.143     bowersj2 1450:         # If this has been filtered out, continue on
                   1451:         if (!(&$filterFunc($curRes))) {
                   1452:             $args->{'isNewBranch'} = 0; # Don't falsely remember this
                   1453:             next;
                   1454:         } 
1.132     bowersj2 1455: 
1.190     bowersj2 1456:         # If this is an empty sequence and we're filtering them, continue on
1.201     bowersj2 1457:         if ($curRes->is_map() && $args->{'suppressEmptySequences'} &&
1.190     bowersj2 1458:             !$curRes->{DATA}->{HAS_VISIBLE_CHILDREN}) {
                   1459:             next;
                   1460:         }
                   1461: 
1.153     bowersj2 1462:         # If we're suppressing navmaps and this is a navmap, continue on
                   1463:         if ($suppressNavmap && $curRes->src() =~ /^\/adm\/navmaps/) {
                   1464:             next;
                   1465:         }
                   1466: 
1.191     bowersj2 1467:         $args->{'counter'}++;
                   1468: 
1.132     bowersj2 1469:         # Does it have multiple parts?
1.133     bowersj2 1470:         $args->{'multipart'} = 0;
                   1471:         $args->{'condensed'} = 0;
1.132     bowersj2 1472:         my @parts;
                   1473:             
                   1474:         # Decide what parts to show.
1.133     bowersj2 1475:         if ($curRes->is_problem() && $showParts) {
1.132     bowersj2 1476:             @parts = @{$curRes->parts()};
1.192     bowersj2 1477:             $args->{'multipart'} = $curRes->multipart();
1.132     bowersj2 1478:             
                   1479:             if ($condenseParts) { # do the condensation
                   1480:                 if (!$curRes->opendate("0")) {
1.162     bowersj2 1481:                     @parts = ();
1.133     bowersj2 1482:                     $args->{'condensed'} = 1;
1.132     bowersj2 1483:                 }
1.133     bowersj2 1484:                 if (!$args->{'condensed'}) {
1.132     bowersj2 1485:                     # Decide whether to condense based on similarity
1.192     bowersj2 1486:                     my $status = $curRes->status($parts[0]);
                   1487:                     my $due = $curRes->duedate($parts[0]);
                   1488:                     my $open = $curRes->opendate($parts[0]);
1.132     bowersj2 1489:                     my $statusAllSame = 1;
                   1490:                     my $dueAllSame = 1;
                   1491:                     my $openAllSame = 1;
1.192     bowersj2 1492:                     for (my $i = 1; $i < scalar(@parts); $i++) {
1.132     bowersj2 1493:                         if ($curRes->status($parts[$i]) != $status){
                   1494:                             $statusAllSame = 0;
                   1495:                         }
                   1496:                         if ($curRes->duedate($parts[$i]) != $due ) {
                   1497:                             $dueAllSame = 0;
                   1498:                         }
                   1499:                         if ($curRes->opendate($parts[$i]) != $open) {
                   1500:                             $openAllSame = 0;
                   1501:                         }
                   1502:                     }
                   1503:                     # $*allSame is true if all the statuses were
                   1504:                     # the same. Now, if they are all the same and
                   1505:                     # match one of the statuses to condense, or they
                   1506:                     # are all open with the same due date, or they are
                   1507:                     # all OPEN_LATER with the same open date, display the
                   1508:                     # status of the first non-zero part (to get the 'correct'
                   1509:                     # status right, since 0 is never 'correct' or 'open').
                   1510:                     if (($statusAllSame && defined($condenseStatuses{$status})) ||
                   1511:                         ($dueAllSame && $status == $curRes->OPEN && $statusAllSame)||
                   1512:                         ($openAllSame && $status == $curRes->OPEN_LATER && $statusAllSame) ){
1.192     bowersj2 1513:                         @parts = ($parts[0]);
1.133     bowersj2 1514:                         $args->{'condensed'} = 1;
1.132     bowersj2 1515:                     }
                   1516:                 }
1.198     bowersj2 1517: 		# Multipart problem with one part: always "condense" (happens
                   1518: 		#  to match the desirable behavior)
                   1519: 		if ($curRes->countParts() == 1) {
                   1520: 		    @parts = ($parts[0]);
                   1521: 		    $args->{'condensed'} = 1;
                   1522: 		}
1.132     bowersj2 1523:             }
1.157     bowersj2 1524:         } 
1.132     bowersj2 1525:             
                   1526:         # If the multipart problem was condensed, "forget" it was multipart
                   1527:         if (scalar(@parts) == 1) {
1.133     bowersj2 1528:             $args->{'multipart'} = 0;
1.192     bowersj2 1529:         } else {
                   1530:             # Add part 0 so we display it correctly.
                   1531:             unshift @parts, '0';
1.132     bowersj2 1532:         }
                   1533: 
                   1534:         # Now, we've decided what parts to show. Loop through them and
                   1535:         # show them.
1.192     bowersj2 1536:         foreach my $part (@parts) {
1.132     bowersj2 1537:             $rownum ++;
                   1538:             my $backgroundColor = $backgroundColors[$rownum % scalar(@backgroundColors)];
                   1539:             
                   1540:             $result .= "  <tr bgcolor='$backgroundColor'>\n";
1.134     bowersj2 1541: 
                   1542:             # Set up some data about the parts that the cols might want
                   1543:             my $filter = $it->{FILTER};
                   1544:             my $stack = $it->getStack();
                   1545:             my $src = getLinkForResource($stack);
1.249     www      1546:             my $anchor='';
                   1547:             if ($src=~s/(\#.*$)//) {
                   1548: 		$anchor=$1;
                   1549: 	    }
1.134     bowersj2 1550:             my $srcHasQuestion = $src =~ /\?/;
                   1551:             $args->{"resourceLink"} = $src.
                   1552:                 ($srcHasQuestion?'&':'?') .
1.249     www      1553:                 'symb=' . &Apache::lonnet::escape($curRes->symb()).
                   1554: 		$anchor;
1.132     bowersj2 1555:             
                   1556:             # Now, display each column.
                   1557:             foreach my $col (@$cols) {
1.139     bowersj2 1558:                 my $colHTML = '';
                   1559:                 if (ref($col)) {
                   1560:                     $colHTML .= &$col($curRes, $part, $args);
                   1561:                 } else {
                   1562:                     $colHTML .= &{$preparedColumns[$col]}($curRes, $part, $args);
                   1563:                 }
1.132     bowersj2 1564: 
1.133     bowersj2 1565:                 # If this is the first column and it's time to print
                   1566:                 # the anchor, do so
                   1567:                 if ($col == $cols->[0] && 
                   1568:                     $args->{'counter'} == $args->{'currentJumpIndex'} - 
1.139     bowersj2 1569:                     $currentJumpDelta) {
                   1570:                     # Jam the anchor after the <td> tag;
                   1571:                     # necessary for valid HTML (which Mozilla requires)
                   1572:                     $colHTML =~ s/\>/\>\<a name="curloc" \/\>/;
1.133     bowersj2 1573:                     $displayedJumpMarker = 1;
                   1574:                 }
1.139     bowersj2 1575:                 $result .= $colHTML . "\n";
1.132     bowersj2 1576:             }
1.139     bowersj2 1577:             $result .= "    </tr>\n";
1.140     bowersj2 1578:             $args->{'isNewBranch'} = 0;
1.139     bowersj2 1579:         }
1.153     bowersj2 1580: 
1.139     bowersj2 1581:         if ($r && $rownum % 20 == 0) {
                   1582:             $r->print($result);
                   1583:             $result = "";
                   1584:             $r->rflush();
1.132     bowersj2 1585:         }
1.156     bowersj2 1586:     } continue {
1.208     bowersj2 1587: 	if ($r) {
                   1588: 	    # If we have the connection, make sure the user is still connected
                   1589: 	    my $c = $r->connection;
                   1590: 	    if ($c->aborted()) {
                   1591: 		# Who cares what we do, nobody will see it anyhow.
                   1592: 		return '';
                   1593: 	    }
                   1594: 	}
1.132     bowersj2 1595:     }
                   1596:     
1.134     bowersj2 1597:     # Print out the part that jumps to #curloc if it exists
1.159     bowersj2 1598:     # delay needed because the browser is processing the jump before
                   1599:     # it finishes rendering, so it goes to the wrong place!
                   1600:     # onload might be better, but this routine has no access to that.
                   1601:     # On mozilla, the 0-millisecond timeout seems to prevent this;
                   1602:     # it's quite likely this might fix other browsers, too, and 
                   1603:     # certainly won't hurt anything.
1.139     bowersj2 1604:     if ($displayedJumpMarker) {
1.247     albertel 1605:         $result .= "
                   1606: <script>
                   1607: if (location.href.indexOf('#curloc')==-1) {
                   1608:     setTimeout(\"location += '#curloc';\", 0)
                   1609: }
                   1610: </script>";
1.134     bowersj2 1611:     }
                   1612: 
1.132     bowersj2 1613:     $result .= "</table>";
1.140     bowersj2 1614:     
                   1615:     if ($r) {
                   1616:         $r->print($result);
                   1617:         $result = "";
                   1618:         $r->rflush();
                   1619:     }
                   1620:         
1.175     bowersj2 1621:     if ($mustCloseNavMap) { $navmap->untieHashes(); } 
1.132     bowersj2 1622: 
                   1623:     return $result;
                   1624: }
                   1625: 
1.133     bowersj2 1626: 1;
                   1627: 
                   1628: package Apache::lonnavmaps::navmap;
                   1629: 
                   1630: =pod
                   1631: 
1.216     bowersj2 1632: =head1 Object: Apache::lonnavmaps::navmap
1.133     bowersj2 1633: 
1.217     bowersj2 1634: =head2 Overview
1.133     bowersj2 1635: 
1.217     bowersj2 1636: The navmap object's job is to provide access to the resources
                   1637: in the course as Apache::lonnavmaps::resource objects, and to
                   1638: query and manage the relationship between those resource objects.
                   1639: 
                   1640: Generally, you'll use the navmap object in one of three basic ways.
                   1641: In order of increasing complexity and power:
                   1642: 
                   1643: =over 4
                   1644: 
                   1645: =item * C<$navmap-E<gt>getByX>, where X is B<Id>, B<Symb>, B<Url> or B<MapPc>. This provides
                   1646:     various ways to obtain resource objects, based on various identifiers.
                   1647:     Use this when you want to request information about one object or 
                   1648:     a handful of resources you already know the identities of, from some
                   1649:     other source. For more about Ids, Symbs, and MapPcs, see the
                   1650:     Resource documentation. Note that Url should be a B<last resort>,
                   1651:     not your first choice; it only works when there is only one
                   1652:     instance of the resource in the course, which only applies to
                   1653:     maps, and even that may change in the future.
                   1654: 
                   1655: =item * C<my @resources = $navmap-E<gt>retrieveResources(args)>. This
                   1656:     retrieves resources matching some criterion and returns them
                   1657:     in a flat array, with no structure information. Use this when
                   1658:     you are manipulating a series of resources, based on what map
                   1659:     the are in, but do not care about branching, or exactly how
                   1660:     the maps and resources are related. This is the most common case.
                   1661: 
                   1662: =item * C<$it = $navmap-E<gt>getIterator(args)>. This allows you traverse
                   1663:     the course's navmap in various ways without writing the traversal
                   1664:     code yourself. See iterator documentation below. Use this when
                   1665:     you need to know absolutely everything about the course, including
                   1666:     branches and the precise relationship between maps and resources.
                   1667: 
                   1668: =back
                   1669: 
                   1670: =head2 Creation And Destruction
                   1671: 
                   1672: To create a navmap object, use the following function:
1.133     bowersj2 1673: 
                   1674: =over 4
                   1675: 
1.221     bowersj2 1676: =item * B<Apache::lonnavmaps::navmap-E<gt>new>():
1.133     bowersj2 1677: 
1.221     bowersj2 1678: Creates a new navmap object. Returns the navmap object if this is
                   1679: successful, or B<undef> if not.
1.174     albertel 1680: 
1.216     bowersj2 1681: =back
                   1682: 
1.217     bowersj2 1683: When you are done with the $navmap object, you I<must> call 
                   1684: $navmap->untieHashes(), or you'll prevent the current user from using that 
                   1685: course until the web server is restarted. (!)
                   1686: 
1.216     bowersj2 1687: =head2 Methods
                   1688: 
                   1689: =over 4
                   1690: 
1.174     albertel 1691: =item * B<getIterator>(first, finish, filter, condition):
                   1692: 
                   1693: See iterator documentation below.
1.133     bowersj2 1694: 
                   1695: =cut
                   1696: 
                   1697: use strict;
                   1698: use GDBM_File;
                   1699: 
                   1700: sub new {
                   1701:     # magic invocation to create a class instance
                   1702:     my $proto = shift;
                   1703:     my $class = ref($proto) || $proto;
                   1704:     my $self = {};
                   1705: 
                   1706:     # Resource cache stores navmap resources as we reference them. We generate
                   1707:     # them on-demand so we don't pay for creating resources unless we use them.
                   1708:     $self->{RESOURCE_CACHE} = {};
                   1709: 
                   1710:     # Network failure flag, if we accessed the course or user opt and
                   1711:     # failed
                   1712:     $self->{NETWORK_FAILURE} = 0;
                   1713: 
                   1714:     # tie the nav hash
                   1715: 
1.168     bowersj2 1716:     my %navmaphash;
                   1717:     my %parmhash;
1.220     bowersj2 1718:     my $courseFn = $ENV{"request.course.fn"};
                   1719:     if (!(tie(%navmaphash, 'GDBM_File', "${courseFn}.db",
1.133     bowersj2 1720:               &GDBM_READER(), 0640))) {
                   1721:         return undef;
                   1722:     }
                   1723:     
1.220     bowersj2 1724:     if (!(tie(%parmhash, 'GDBM_File', "${courseFn}_parms.db",
1.133     bowersj2 1725:               &GDBM_READER(), 0640)))
                   1726:     {
1.170     matthew  1727:         untie %{$self->{PARM_HASH}};
1.133     bowersj2 1728:         return undef;
                   1729:     }
                   1730: 
1.199     bowersj2 1731:     $self->{NAV_HASH} = \%navmaphash;
1.168     bowersj2 1732:     $self->{PARM_HASH} = \%parmhash;
1.221     bowersj2 1733:     $self->{PARM_CACHE} = {};
1.133     bowersj2 1734: 
                   1735:     bless($self);
                   1736:         
                   1737:     return $self;
                   1738: }
                   1739: 
1.221     bowersj2 1740: sub generate_course_user_opt {
1.133     bowersj2 1741:     my $self = shift;
1.221     bowersj2 1742:     if ($self->{COURSE_USER_OPT_GENERATED}) { return; }
1.133     bowersj2 1743: 
1.221     bowersj2 1744:     my $uname=$ENV{'user.name'};
                   1745:     my $udom=$ENV{'user.domain'};
                   1746:     my $uhome=$ENV{'user.home'};
                   1747:     my $cid=$ENV{'request.course.id'};
                   1748:     my $chome=$ENV{'course.'.$cid.'.home'};
                   1749:     my ($cdom,$cnum)=split(/\_/,$cid);
                   1750:     
                   1751:     my $userprefix=$uname.'_'.$udom.'_';
                   1752:     
                   1753:     my %courserdatas; my %useropt; my %courseopt; my %userrdatas;
                   1754:     unless ($uhome eq 'no_host') { 
1.133     bowersj2 1755: # ------------------------------------------------- Get coursedata (if present)
1.221     bowersj2 1756: 	unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
                   1757: 	    my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
                   1758: 					     ':resourcedata',$chome);
                   1759: 	    # Check for network failure
                   1760: 	    if ( $reply =~ /no.such.host/i || $reply =~ /con_lost/i) {
                   1761: 		$self->{NETWORK_FAILURE} = 1;
                   1762: 	    } elsif ($reply!~/^error\:/) {
                   1763: 		$courserdatas{$cid}=$reply;
                   1764: 		$courserdatas{$cid.'.last_cache'}=time;
                   1765: 	    }
                   1766: 	}
                   1767: 	foreach (split(/\&/,$courserdatas{$cid})) {
                   1768: 	    my ($name,$value)=split(/\=/,$_);
                   1769: 	    $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
                   1770: 		&Apache::lonnet::unescape($value);
                   1771: 	}
1.133     bowersj2 1772: # --------------------------------------------------- Get userdata (if present)
1.221     bowersj2 1773: 	unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
                   1774: 	    my $reply=&Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
                   1775: 	    if ($reply!~/^error\:/) {
                   1776: 		$userrdatas{$uname.'___'.$udom}=$reply;
                   1777: 		$userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
                   1778: 	    }
                   1779: 	    # check to see if network failed
                   1780: 	    elsif ( $reply=~/no.such.host/i || $reply=~/con.*lost/i )
                   1781: 	    {
                   1782: 		$self->{NETWORK_FAILURE} = 1;
                   1783: 	    }
                   1784: 	}
                   1785: 	foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
                   1786: 	    my ($name,$value)=split(/\=/,$_);
                   1787: 	    $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
                   1788: 		&Apache::lonnet::unescape($value);
                   1789: 	}
                   1790: 	$self->{COURSE_OPT} = \%courseopt;
                   1791: 	$self->{USER_OPT} = \%useropt;
                   1792:     }
                   1793: 
                   1794:     $self->{COURSE_USER_OPT_GENERATED} = 1;
                   1795:     
                   1796:     return;
                   1797: }
                   1798: 
                   1799: sub generate_email_discuss_status {
                   1800:     my $self = shift;
                   1801:     if ($self->{EMAIL_DISCUSS_GENERATED}) { return; }
1.133     bowersj2 1802: 
1.221     bowersj2 1803:     my $cid=$ENV{'request.course.id'};
                   1804:     my ($cdom,$cnum)=split(/\_/,$cid);
                   1805:     
                   1806:     my %emailstatus = &Apache::lonnet::dump('email_status');
                   1807:     my $logoutTime = $emailstatus{'logout'};
                   1808:     my $courseLeaveTime = $emailstatus{'logout_'.$ENV{'request.course.id'}};
                   1809:     $self->{LAST_CHECK} = (($courseLeaveTime > $logoutTime) ?
                   1810: 			   $courseLeaveTime : $logoutTime);
                   1811:     my %discussiontime = &Apache::lonnet::dump('discussiontimes', 
                   1812: 					       $cdom, $cnum);
                   1813:     my %feedback=();
                   1814:     my %error=();
                   1815:     my $keys = &Apache::lonnet::reply('keys:'.
                   1816: 				      $ENV{'user.domain'}.':'.
                   1817: 				      $ENV{'user.name'}.':nohist_email',
                   1818: 				      $ENV{'user.home'});
                   1819:     
                   1820:     foreach my $msgid (split(/\&/, $keys)) {
                   1821: 	$msgid=&Apache::lonnet::unescape($msgid);
                   1822: 	my $plain=&Apache::lonnet::unescape(&Apache::lonnet::unescape($msgid));
                   1823: 	if ($plain=~/(Error|Feedback) \[([^\]]+)\]/) {
                   1824: 	    my ($what,$url)=($1,$2);
                   1825: 	    my %status=
                   1826: 		&Apache::lonnet::get('email_status',[$msgid]);
                   1827: 	    if ($status{$msgid}=~/^error\:/) { 
                   1828: 		$status{$msgid}=''; 
                   1829: 	    }
                   1830: 	    
                   1831: 	    if (($status{$msgid} eq 'new') || 
                   1832: 		(!$status{$msgid})) { 
                   1833: 		if ($what eq 'Error') {
                   1834: 		    $error{$url}.=','.$msgid; 
                   1835: 		} else {
                   1836: 		    $feedback{$url}.=','.$msgid;
                   1837: 		}
                   1838: 	    }
                   1839: 	}
1.211     bowersj2 1840:     }
1.221     bowersj2 1841:     
                   1842:     $self->{FEEDBACK} = \%feedback;
                   1843:     $self->{ERROR_MSG} = \%error; # what is this? JB
                   1844:     $self->{DISCUSSION_TIME} = \%discussiontime;
                   1845:     $self->{EMAIL_STATUS} = \%emailstatus;
                   1846:     
                   1847:     $self->{EMAIL_DISCUSS_GENERATED} = 1;
                   1848: }
                   1849: 
                   1850: sub get_user_data {
                   1851:     my $self = shift;
                   1852:     if ($self->{RETRIEVED_USER_DATA}) { return; }
1.211     bowersj2 1853: 
1.221     bowersj2 1854:     # Retrieve performance data on problems
                   1855:     my %student_data = Apache::lonnet::currentdump($ENV{'request.course.id'},
                   1856: 						   $ENV{'user.domain'},
                   1857: 						   $ENV{'user.name'});
                   1858:     $self->{STUDENT_DATA} = \%student_data;
1.133     bowersj2 1859: 
1.221     bowersj2 1860:     $self->{RETRIEVED_USER_DATA} = 1;
1.133     bowersj2 1861: }
                   1862: 
                   1863: # Internal function: Takes a key to look up in the nav hash and implements internal
                   1864: # memory caching of that key.
                   1865: sub navhash {
                   1866:     my $self = shift; my $key = shift;
                   1867:     return $self->{NAV_HASH}->{$key};
                   1868: }
                   1869: 
1.217     bowersj2 1870: =pod
                   1871: 
                   1872: =item * B<courseMapDefined>(): Returns true if the course map is defined, 
                   1873:     false otherwise. Undefined course maps indicate an error somewhere in
                   1874:     LON-CAPA, and you will not be able to proceed with using the navmap.
                   1875:     See the B<NAV> screen for an example of using this.
                   1876: 
                   1877: =cut
                   1878: 
1.133     bowersj2 1879: # Checks to see if coursemap is defined, matching test in old lonnavmaps
                   1880: sub courseMapDefined {
                   1881:     my $self = shift;
                   1882:     my $uri = &Apache::lonnet::clutter($ENV{'request.course.uri'});
                   1883: 
                   1884:     my $firstres = $self->navhash("map_start_$uri");
                   1885:     my $lastres = $self->navhash("map_finish_$uri");
                   1886:     return $firstres && $lastres;
                   1887: }
                   1888: 
                   1889: sub getIterator {
                   1890:     my $self = shift;
                   1891:     my $iterator = Apache::lonnavmaps::iterator->new($self, shift, shift,
                   1892:                                                      shift, undef, shift);
                   1893:     return $iterator;
                   1894: }
                   1895: 
                   1896: # unties the hash when done
                   1897: sub untieHashes {
1.168     bowersj2 1898:     my $self = shift;
1.170     matthew  1899:     untie %{$self->{NAV_HASH}};
                   1900:     untie %{$self->{PARM_HASH}};
1.133     bowersj2 1901: }
                   1902: 
                   1903: # Private method: Does the given resource (as a symb string) have
                   1904: # current discussion? Returns 0 if chat/mail data not extracted.
                   1905: sub hasDiscussion {
                   1906:     my $self = shift;
                   1907:     my $symb = shift;
1.221     bowersj2 1908:     
                   1909:     $self->generate_email_discuss_status();
                   1910: 
1.133     bowersj2 1911:     if (!defined($self->{DISCUSSION_TIME})) { return 0; }
                   1912: 
                   1913:     #return defined($self->{DISCUSSION_TIME}->{$symb});
                   1914:     return $self->{DISCUSSION_TIME}->{$symb} >
                   1915:            $self->{LAST_CHECK};
                   1916: }
                   1917: 
                   1918: # Private method: Does the given resource (as a symb string) have
                   1919: # current feedback? Returns the string in the feedback hash, which
                   1920: # will be false if it does not exist.
                   1921: sub getFeedback { 
                   1922:     my $self = shift;
                   1923:     my $symb = shift;
                   1924: 
1.221     bowersj2 1925:     $self->generate_email_discuss_status();
                   1926: 
1.133     bowersj2 1927:     if (!defined($self->{FEEDBACK})) { return ""; }
                   1928:     
                   1929:     return $self->{FEEDBACK}->{$symb};
                   1930: }
                   1931: 
                   1932: # Private method: Get the errors for that resource (by source).
                   1933: sub getErrors { 
                   1934:     my $self = shift;
                   1935:     my $src = shift;
1.221     bowersj2 1936: 
                   1937:     $self->generate_email_discuss_status();
                   1938: 
1.133     bowersj2 1939:     if (!defined($self->{ERROR_MSG})) { return ""; }
                   1940:     return $self->{ERROR_MSG}->{$src};
                   1941: }
                   1942: 
                   1943: =pod
                   1944: 
1.174     albertel 1945: =item * B<getById>(id):
                   1946: 
                   1947: Based on the ID of the resource (1.1, 3.2, etc.), get a resource
                   1948: object for that resource. This method, or other methods that use it
                   1949: (as in the resource object) is the only proper way to obtain a
                   1950: resource object.
1.133     bowersj2 1951: 
1.194     bowersj2 1952: =item * B<getBySymb>(symb):
                   1953: 
                   1954: Based on the symb of the resource, get a resource object for that
                   1955: resource. This is one of the proper ways to get a resource object.
                   1956: 
                   1957: =item * B<getMapByMapPc>(map_pc):
                   1958: 
                   1959: Based on the map_pc of the resource, get a resource object for
                   1960: the given map. This is one of the proper ways to get a resource object.
                   1961: 
1.133     bowersj2 1962: =cut
                   1963: 
                   1964: # The strategy here is to cache the resource objects, and only construct them
                   1965: # as we use them. The real point is to prevent reading any more from the tied
                   1966: # hash then we have to, which should hopefully alleviate speed problems.
                   1967: 
                   1968: sub getById {
                   1969:     my $self = shift;
                   1970:     my $id = shift;
                   1971: 
                   1972:     if (defined ($self->{RESOURCE_CACHE}->{$id}))
                   1973:     {
                   1974:         return $self->{RESOURCE_CACHE}->{$id};
                   1975:     }
                   1976: 
                   1977:     # resource handles inserting itself into cache.
                   1978:     # Not clear why the quotes are necessary, but as of this
                   1979:     # writing it doesn't work without them.
                   1980:     return "Apache::lonnavmaps::resource"->new($self, $id);
1.132     bowersj2 1981: }
1.133     bowersj2 1982: 
1.172     bowersj2 1983: sub getBySymb {
                   1984:     my $self = shift;
                   1985:     my $symb = shift;
1.228     albertel 1986:     my ($mapUrl, $id, $filename) = &Apache::lonnet::decode_symb($symb);
1.172     bowersj2 1987:     my $map = $self->getResourceByUrl($mapUrl);
                   1988:     return $self->getById($map->map_pc() . '.' . $id);
1.194     bowersj2 1989: }
                   1990: 
                   1991: sub getByMapPc {
                   1992:     my $self = shift;
                   1993:     my $map_pc = shift;
                   1994:     my $map_id = $self->{NAV_HASH}->{'map_id_' . $map_pc};
                   1995:     $map_id = $self->{NAV_HASH}->{'ids_' . $map_id};
                   1996:     return $self->getById($map_id);
1.172     bowersj2 1997: }
                   1998: 
1.133     bowersj2 1999: =pod
                   2000: 
1.174     albertel 2001: =item * B<firstResource>():
                   2002: 
                   2003: Returns a resource object reference corresponding to the first
                   2004: resource in the navmap.
1.133     bowersj2 2005: 
                   2006: =cut
                   2007: 
                   2008: sub firstResource {
                   2009:     my $self = shift;
                   2010:     my $firstResource = $self->navhash('map_start_' .
                   2011:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
                   2012:     return $self->getById($firstResource);
1.132     bowersj2 2013: }
1.133     bowersj2 2014: 
                   2015: =pod
                   2016: 
1.174     albertel 2017: =item * B<finishResource>():
                   2018: 
                   2019: Returns a resource object reference corresponding to the last resource
                   2020: in the navmap.
1.133     bowersj2 2021: 
                   2022: =cut
                   2023: 
                   2024: sub finishResource {
                   2025:     my $self = shift;
                   2026:     my $firstResource = $self->navhash('map_finish_' .
                   2027:                      &Apache::lonnet::clutter($ENV{'request.course.uri'}));
                   2028:     return $self->getById($firstResource);
1.132     bowersj2 2029: }
1.133     bowersj2 2030: 
                   2031: # Parmval reads the parm hash and cascades the lookups. parmval_real does
                   2032: # the actual lookup; parmval caches the results.
                   2033: sub parmval {
                   2034:     my $self = shift;
                   2035:     my ($what,$symb)=@_;
                   2036:     my $hashkey = $what."|||".$symb;
                   2037: 
                   2038:     if (defined($self->{PARM_CACHE}->{$hashkey})) {
                   2039:         return $self->{PARM_CACHE}->{$hashkey};
                   2040:     }
                   2041: 
                   2042:     my $result = $self->parmval_real($what, $symb);
                   2043:     $self->{PARM_CACHE}->{$hashkey} = $result;
                   2044:     return $result;
1.132     bowersj2 2045: }
                   2046: 
1.133     bowersj2 2047: sub parmval_real {
                   2048:     my $self = shift;
1.219     albertel 2049:     my ($what,$symb,$recurse) = @_;
1.133     bowersj2 2050: 
1.221     bowersj2 2051:     # Make sure the {USER_OPT} and {COURSE_OPT} hashes are populated
                   2052:     $self->generate_course_user_opt();
                   2053: 
1.133     bowersj2 2054:     my $cid=$ENV{'request.course.id'};
                   2055:     my $csec=$ENV{'request.course.sec'};
                   2056:     my $uname=$ENV{'user.name'};
                   2057:     my $udom=$ENV{'user.domain'};
                   2058: 
                   2059:     unless ($symb) { return ''; }
                   2060:     my $result='';
                   2061: 
1.226     www      2062:     my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
1.133     bowersj2 2063: 
                   2064: # ----------------------------------------------------- Cascading lookup scheme
                   2065:     my $rwhat=$what;
                   2066:     $what=~s/^parameter\_//;
                   2067:     $what=~s/\_/\./;
                   2068: 
                   2069:     my $symbparm=$symb.'.'.$what;
                   2070:     my $mapparm=$mapname.'___(all).'.$what;
                   2071:     my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
                   2072: 
                   2073:     my $seclevel= $usercourseprefix.'.['.$csec.'].'.$what;
                   2074:     my $seclevelr=$usercourseprefix.'.['.$csec.'].'.$symbparm;
                   2075:     my $seclevelm=$usercourseprefix.'.['.$csec.'].'.$mapparm;
                   2076: 
                   2077:     my $courselevel= $usercourseprefix.'.'.$what;
                   2078:     my $courselevelr=$usercourseprefix.'.'.$symbparm;
                   2079:     my $courselevelm=$usercourseprefix.'.'.$mapparm;
                   2080: 
                   2081:     my $useropt = $self->{USER_OPT};
                   2082:     my $courseopt = $self->{COURSE_OPT};
                   2083:     my $parmhash = $self->{PARM_HASH};
                   2084: 
                   2085: # ---------------------------------------------------------- first, check user
                   2086:     if ($uname and defined($useropt)) {
                   2087:         if (defined($$useropt{$courselevelr})) { return $$useropt{$courselevelr}; }
                   2088:         if (defined($$useropt{$courselevelm})) { return $$useropt{$courselevelm}; }
                   2089:         if (defined($$useropt{$courselevel})) { return $$useropt{$courselevel}; }
                   2090:     }
                   2091: 
                   2092: # ------------------------------------------------------- second, check course
                   2093:     if ($csec and defined($courseopt)) {
                   2094:         if (defined($$courseopt{$seclevelr})) { return $$courseopt{$seclevelr}; }
                   2095:         if (defined($$courseopt{$seclevelm})) { return $$courseopt{$seclevelm}; }
                   2096:         if (defined($$courseopt{$seclevel})) { return $$courseopt{$seclevel}; }
                   2097:     }
                   2098: 
                   2099:     if (defined($courseopt)) {
                   2100:         if (defined($$courseopt{$courselevelr})) { return $$courseopt{$courselevelr}; }
                   2101:         if (defined($$courseopt{$courselevelm})) { return $$courseopt{$courselevelm}; }
                   2102:         if (defined($$courseopt{$courselevel})) { return $$courseopt{$courselevel}; }
                   2103:     }
                   2104: 
                   2105: # ----------------------------------------------------- third, check map parms
                   2106: 
                   2107:     my $thisparm=$$parmhash{$symbparm};
                   2108:     if (defined($thisparm)) { return $thisparm; }
                   2109: 
                   2110: # ----------------------------------------------------- fourth , check default
                   2111: 
1.246     albertel 2112:     my $meta_rwhat=$rwhat;
                   2113:     $meta_rwhat=~s/\./_/g;
                   2114:     my $default=&Apache::lonnet::metadata($fn,$meta_rwhat);
                   2115:     if (defined($default)) { return $default}
                   2116:     $default=&Apache::lonnet::metadata($fn,'parameter_'.$meta_rwhat);
1.133     bowersj2 2117:     if (defined($default)) { return $default}
                   2118: 
                   2119: # --------------------------------------------------- fifth , cascade up parts
                   2120: 
                   2121:     my ($space,@qualifier)=split(/\./,$rwhat);
                   2122:     my $qualifier=join('.',@qualifier);
                   2123:     unless ($space eq '0') {
1.160     albertel 2124: 	my @parts=split(/_/,$space);
                   2125: 	my $id=pop(@parts);
                   2126: 	my $part=join('_',@parts);
                   2127: 	if ($part eq '') { $part='0'; }
1.219     albertel 2128: 	my $partgeneral=$self->parmval($part.".$qualifier",$symb,1);
1.160     albertel 2129: 	if (defined($partgeneral)) { return $partgeneral; }
1.133     bowersj2 2130:     }
1.219     albertel 2131:     if ($recurse) { return undef; }
                   2132:     my $pack_def=&Apache::lonnet::packages_tab_default($fn,'resource.'.$what);
                   2133:     if (defined($pack_def)) { return $pack_def; }
1.133     bowersj2 2134:     return '';
1.145     bowersj2 2135: }
                   2136: 
1.174     albertel 2137: =pod
1.145     bowersj2 2138: 
1.174     albertel 2139: =item * B<getResourceByUrl>(url):
1.145     bowersj2 2140: 
1.174     albertel 2141: Retrieves a resource object by URL of the resource. If passed a
                   2142: resource object, it will simply return it, so it is safe to use this
                   2143: method in code like "$res = $navmap->getResourceByUrl($res)", if
                   2144: you're not sure if $res is already an object, or just a URL. If the
                   2145: resource appears multiple times in the course, only the first instance
                   2146: will be returned. As a result, this is probably useful only for maps.
                   2147: 
                   2148: =item * B<retrieveResources>(map, filterFunc, recursive, bailout):
                   2149: 
                   2150: The map is a specification of a map to retreive the resources from,
                   2151: either as a url or as an object. The filterFunc is a reference to a
                   2152: function that takes a resource object as its one argument and returns
                   2153: true if the resource should be included, or false if it should not
                   2154: be. If recursive is true, the map will be recursively examined,
                   2155: otherwise it will not be. If bailout is true, the function will return
                   2156: as soon as it finds a resource, if false it will finish. By default,
                   2157: the map is the top-level map of the course, filterFunc is a function
                   2158: that always returns 1, recursive is true, bailout is false. The
                   2159: resources will be returned in a list containing the resource objects
                   2160: for the corresponding resources, with B<no structure information> in
                   2161: the list; regardless of branching, recursion, etc., it will be a flat
                   2162: list.
                   2163: 
                   2164: Thus, this is suitable for cases where you don't want the structure,
                   2165: just a list of all resources. It is also suitable for finding out how
                   2166: many resources match a given description; for this use, if all you
                   2167: want to know is if I<any> resources match the description, the bailout
                   2168: parameter will allow you to avoid potentially expensive enumeration of
                   2169: all matching resources.
1.145     bowersj2 2170: 
1.174     albertel 2171: =item * B<hasResources>(map, filterFunc, recursive):
1.145     bowersj2 2172: 
1.174     albertel 2173: Convience method for
1.146     bowersj2 2174: 
                   2175:  scalar(retrieveResources($map, $filterFunc, $recursive, 1)) > 0
                   2176: 
1.174     albertel 2177: which will tell whether the map has resources matching the description
                   2178: in the filter function.
1.146     bowersj2 2179: 
1.145     bowersj2 2180: =cut
                   2181: 
                   2182: sub getResourceByUrl {
                   2183:     my $self = shift;
                   2184:     my $resUrl = shift;
                   2185: 
                   2186:     if (ref($resUrl)) { return $resUrl; }
                   2187: 
                   2188:     $resUrl = &Apache::lonnet::clutter($resUrl);
                   2189:     my $resId = $self->{NAV_HASH}->{'ids_' . $resUrl};
                   2190:     if ($resId =~ /,/) {
                   2191:         $resId = (split (/,/, $resId))[0];
                   2192:     }
                   2193:     if (!$resId) { return ''; }
                   2194:     return $self->getById($resId);
                   2195: }
                   2196: 
                   2197: sub retrieveResources {
                   2198:     my $self = shift;
                   2199:     my $map = shift;
                   2200:     my $filterFunc = shift;
                   2201:     if (!defined ($filterFunc)) {
                   2202:         $filterFunc = sub {return 1;};
                   2203:     }
                   2204:     my $recursive = shift;
                   2205:     if (!defined($recursive)) { $recursive = 1; }
                   2206:     my $bailout = shift;
                   2207:     if (!defined($bailout)) { $bailout = 0; }
                   2208: 
                   2209:     # Create the necessary iterator.
                   2210:     if (!ref($map)) { # assume it's a url of a map.
1.172     bowersj2 2211:         $map = $self->getResourceByUrl($map);
1.145     bowersj2 2212:     }
                   2213: 
1.213     bowersj2 2214:     # If nothing was passed, assume top-level map
                   2215:     if (!$map) {
                   2216: 	$map = $self->getById('0.0');
                   2217:     }
                   2218: 
1.145     bowersj2 2219:     # Check the map's validity.
1.213     bowersj2 2220:     if (!$map->is_map()) {
1.145     bowersj2 2221:         # Oh, to throw an exception.... how I'd love that!
                   2222:         return ();
                   2223:     }
                   2224: 
1.146     bowersj2 2225:     # Get an iterator.
                   2226:     my $it = $self->getIterator($map->map_start(), $map->map_finish(),
1.215     bowersj2 2227:                                 undef, $recursive);
1.146     bowersj2 2228: 
                   2229:     my @resources = ();
                   2230: 
                   2231:     # Run down the iterator and collect the resources.
1.222     bowersj2 2232:     my $curRes;
                   2233: 
                   2234:     while ($curRes = $it->next()) {
1.146     bowersj2 2235:         if (ref($curRes)) {
                   2236:             if (!&$filterFunc($curRes)) {
                   2237:                 next;
                   2238:             }
                   2239: 
                   2240:             push @resources, $curRes;
                   2241: 
                   2242:             if ($bailout) {
                   2243:                 return @resources;
                   2244:             }
                   2245:         }
                   2246: 
                   2247:     }
                   2248: 
                   2249:     return @resources;
                   2250: }
                   2251: 
                   2252: sub hasResource {
                   2253:     my $self = shift;
                   2254:     my $map = shift;
                   2255:     my $filterFunc = shift;
                   2256:     my $recursive = shift;
                   2257:     
                   2258:     return scalar($self->retrieveResources($map, $filterFunc, $recursive, 1)) > 0;
1.133     bowersj2 2259: }
1.51      bowersj2 2260: 
                   2261: 1;
                   2262: 
                   2263: package Apache::lonnavmaps::iterator;
                   2264: 
                   2265: =pod
                   2266: 
                   2267: =back
                   2268: 
1.174     albertel 2269: =head1 Object: navmap Iterator
1.51      bowersj2 2270: 
1.174     albertel 2271: An I<iterator> encapsulates the logic required to traverse a data
                   2272: structure. navmap uses an iterator to traverse the course map
                   2273: according to the criteria you wish to use.
                   2274: 
                   2275: To obtain an iterator, call the B<getIterator>() function of a
                   2276: B<navmap> object. (Do not instantiate Apache::lonnavmaps::iterator
                   2277: directly.) This will return a reference to the iterator:
1.51      bowersj2 2278: 
                   2279: C<my $resourceIterator = $navmap-E<gt>getIterator();>
                   2280: 
                   2281: To get the next thing from the iterator, call B<next>:
                   2282: 
                   2283: C<my $nextThing = $resourceIterator-E<gt>next()>
                   2284: 
                   2285: getIterator behaves as follows:
                   2286: 
                   2287: =over 4
                   2288: 
1.174     albertel 2289: =item * B<getIterator>(firstResource, finishResource, filterHash, condition, forceTop, returnTopMap):
                   2290: 
                   2291: All parameters are optional. firstResource is a resource reference
                   2292: corresponding to where the iterator should start. It defaults to
                   2293: navmap->firstResource() for the corresponding nav map. finishResource
                   2294: corresponds to where you want the iterator to end, defaulting to
                   2295: navmap->finishResource(). filterHash is a hash used as a set
                   2296: containing strings representing the resource IDs, defaulting to
                   2297: empty. Condition is a 1 or 0 that sets what to do with the filter
1.205     bowersj2 2298: hash: If a 0, then only resources that exist IN the filterHash will be
1.174     albertel 2299: recursed on. If it is a 1, only resources NOT in the filterHash will
                   2300: be recursed on. Defaults to 0. forceTop is a boolean value. If it is
                   2301: false (default), the iterator will only return the first level of map
                   2302: that is not just a single, 'redirecting' map. If true, the iterator
                   2303: will return all information, starting with the top-level map,
                   2304: regardless of content. returnTopMap, if true (default false), will
                   2305: cause the iterator to return the top-level map object (resource 0.0)
                   2306: before anything else.
                   2307: 
                   2308: Thus, by default, only top-level resources will be shown. Change the
                   2309: condition to a 1 without changing the hash, and all resources will be
                   2310: shown. Changing the condition to 1 and including some values in the
                   2311: hash will allow you to selectively suppress parts of the navmap, while
                   2312: leaving it on 0 and adding things to the hash will allow you to
                   2313: selectively add parts of the nav map. See the handler code for
                   2314: examples.
                   2315: 
                   2316: The iterator will return either a reference to a resource object, or a
                   2317: token representing something in the map, such as the beginning of a
                   2318: new branch. The possible tokens are:
                   2319: 
                   2320: =over 4
1.51      bowersj2 2321: 
1.222     bowersj2 2322: =item * B<END_ITERATOR>:
                   2323: 
                   2324: The iterator has returned all that it's going to. Further calls to the
                   2325: iterator will just produce more of these. This is a "false" value, and
                   2326: is the only false value the iterator which will be returned, so it can
                   2327: be used as a loop sentinel.
                   2328: 
1.217     bowersj2 2329: =item * B<BEGIN_MAP>:
1.51      bowersj2 2330: 
1.174     albertel 2331: A new map is being recursed into. This is returned I<after> the map
                   2332: resource itself is returned.
1.51      bowersj2 2333: 
1.217     bowersj2 2334: =item * B<END_MAP>:
1.174     albertel 2335: 
                   2336: The map is now done.
1.51      bowersj2 2337: 
1.217     bowersj2 2338: =item * B<BEGIN_BRANCH>:
1.70      bowersj2 2339: 
1.174     albertel 2340: A branch is now starting. The next resource returned will be the first
                   2341: in that branch.
1.70      bowersj2 2342: 
1.217     bowersj2 2343: =item * B<END_BRANCH>:
1.70      bowersj2 2344: 
1.174     albertel 2345: The branch is now done.
1.51      bowersj2 2346: 
                   2347: =back
                   2348: 
1.174     albertel 2349: The tokens are retreivable via methods on the iterator object, i.e.,
                   2350: $iterator->END_MAP.
1.70      bowersj2 2351: 
1.174     albertel 2352: Maps can contain empty resources. The iterator will automatically skip
                   2353: over such resources, but will still treat the structure
                   2354: correctly. Thus, a complicated map with several branches, but
                   2355: consisting entirely of empty resources except for one beginning or
                   2356: ending resource, will cause a lot of BRANCH_STARTs and BRANCH_ENDs,
                   2357: but only one resource will be returned.
1.116     bowersj2 2358: 
1.242     matthew  2359: =back
                   2360: 
1.222     bowersj2 2361: =head2 Normal Usage
                   2362: 
                   2363: Normal usage of the iterator object is to do the following:
                   2364: 
                   2365:  my $it = $navmap->getIterator([your params here]);
                   2366:  my $curRes;
                   2367:  while ($curRes = $it->next()) {
                   2368:    [your logic here]
                   2369:  }
                   2370: 
                   2371: Note that inside of the loop, it's frequently useful to check if
                   2372: "$curRes" is a reference or not with the reference function; only
                   2373: resource objects will be references, and any non-references will 
                   2374: be the tokens described above.
                   2375: 
                   2376: Also note there is some old code floating around that trys to track
                   2377: the depth of the iterator to see when it's done; do not copy that 
                   2378: code. It is difficult to get right and harder to understand then
                   2379: this. They should be migrated to this new style.
1.51      bowersj2 2380: 
                   2381: =cut
                   2382: 
                   2383: # Here are the tokens for the iterator:
                   2384: 
1.222     bowersj2 2385: sub END_ITERATOR { return 0; }
1.51      bowersj2 2386: sub BEGIN_MAP { return 1; }    # begining of a new map
                   2387: sub END_MAP { return 2; }      # end of the map
                   2388: sub BEGIN_BRANCH { return 3; } # beginning of a branch
                   2389: sub END_BRANCH { return 4; }   # end of a branch
1.89      bowersj2 2390: sub FORWARD { return 1; }      # go forward
                   2391: sub BACKWARD { return 2; }
1.51      bowersj2 2392: 
1.96      bowersj2 2393: sub min {
                   2394:     (my $a, my $b) = @_;
                   2395:     if ($a < $b) { return $a; } else { return $b; }
                   2396: }
                   2397: 
1.94      bowersj2 2398: sub new {
                   2399:     # magic invocation to create a class instance
                   2400:     my $proto = shift;
                   2401:     my $class = ref($proto) || $proto;
                   2402:     my $self = {};
                   2403: 
                   2404:     $self->{NAV_MAP} = shift;
                   2405:     return undef unless ($self->{NAV_MAP});
                   2406: 
                   2407:     # Handle the parameters
                   2408:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
                   2409:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
                   2410: 
                   2411:     # If the given resources are just the ID of the resource, get the
                   2412:     # objects
                   2413:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
                   2414:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
                   2415:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
                   2416:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
                   2417: 
                   2418:     $self->{FILTER} = shift;
                   2419: 
                   2420:     # A hash, used as a set, of resource already seen
                   2421:     $self->{ALREADY_SEEN} = shift;
                   2422:     if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
                   2423:     $self->{CONDITION} = shift;
                   2424: 
1.116     bowersj2 2425:     # Do we want to automatically follow "redirection" maps?
                   2426:     $self->{FORCE_TOP} = shift;
                   2427: 
1.162     bowersj2 2428:     # Do we want to return the top-level map object (resource 0.0)?
                   2429:     $self->{RETURN_0} = shift;
                   2430:     # have we done that yet?
                   2431:     $self->{HAVE_RETURNED_0} = 0;
                   2432: 
1.94      bowersj2 2433:     # Now, we need to pre-process the map, by walking forward and backward
                   2434:     # over the parts of the map we're going to look at.
1.96      bowersj2 2435: 
1.97      bowersj2 2436:     # The processing steps are exactly the same, except for a few small 
                   2437:     # changes, so I bundle those up in the following list of two elements:
                   2438:     # (direction_to_iterate, VAL_name, next_resource_method_to_call,
                   2439:     # first_resource).
                   2440:     # This prevents writing nearly-identical code twice.
                   2441:     my @iterations = ( [FORWARD(), 'TOP_DOWN_VAL', 'getNext', 
                   2442:                         'FIRST_RESOURCE'],
                   2443:                        [BACKWARD(), 'BOT_UP_VAL', 'getPrevious', 
                   2444:                         'FINISH_RESOURCE'] );
                   2445: 
1.98      bowersj2 2446:     my $maxDepth = 0; # tracks max depth
                   2447: 
1.116     bowersj2 2448:     # If there is only one resource in this map, and it's a map, we
                   2449:     # want to remember that, so the user can ask for the first map
                   2450:     # that isn't just a redirector.
                   2451:     my $resource; my $resourceCount = 0;
                   2452: 
1.209     bowersj2 2453:     # Documentation on this algorithm can be found in the CVS repository at 
                   2454:     # /docs/lonnavdocs; these "**#**" markers correspond to documentation
                   2455:     # in that file.
1.107     bowersj2 2456:     # **1**
                   2457: 
1.97      bowersj2 2458:     foreach my $pass (@iterations) {
                   2459:         my $direction = $pass->[0];
                   2460:         my $valName = $pass->[1];
                   2461:         my $nextResourceMethod = $pass->[2];
                   2462:         my $firstResourceName = $pass->[3];
                   2463: 
                   2464:         my $iterator = Apache::lonnavmaps::DFSiterator->new($self->{NAV_MAP}, 
                   2465:                                                             $self->{FIRST_RESOURCE},
                   2466:                                                             $self->{FINISH_RESOURCE},
                   2467:                                                             {}, undef, 0, $direction);
1.96      bowersj2 2468:     
1.97      bowersj2 2469:         # prime the recursion
                   2470:         $self->{$firstResourceName}->{DATA}->{$valName} = 0;
1.222     bowersj2 2471: 	$iterator->next();
1.97      bowersj2 2472:         my $curRes = $iterator->next();
1.222     bowersj2 2473: 	my $depth = 1;
                   2474:         while ($depth > 0) {
                   2475: 	    if ($curRes == $iterator->BEGIN_MAP()) { $depth++; }
                   2476: 	    if ($curRes == $iterator->END_MAP()) { $depth--; }
                   2477: 
1.97      bowersj2 2478:             if (ref($curRes)) {
1.116     bowersj2 2479:                 # If there's only one resource, this will save it
1.117     bowersj2 2480:                 # we have to filter empty resources from consideration here,
                   2481:                 # or even "empty", redirecting maps have two (start & finish)
                   2482:                 # or three (start, finish, plus redirector)
                   2483:                 if($direction == FORWARD && $curRes->src()) { 
                   2484:                     $resource = $curRes; $resourceCount++; 
                   2485:                 }
1.97      bowersj2 2486:                 my $resultingVal = $curRes->{DATA}->{$valName};
                   2487:                 my $nextResources = $curRes->$nextResourceMethod();
1.116     bowersj2 2488:                 my $nextCount = scalar(@{$nextResources});
1.104     bowersj2 2489: 
1.116     bowersj2 2490:                 if ($nextCount == 1) { # **3**
1.97      bowersj2 2491:                     my $current = $nextResources->[0]->{DATA}->{$valName} || 999999999;
                   2492:                     $nextResources->[0]->{DATA}->{$valName} = min($resultingVal, $current);
                   2493:                 }
                   2494:                 
1.116     bowersj2 2495:                 if ($nextCount > 1) { # **4**
1.97      bowersj2 2496:                     foreach my $res (@{$nextResources}) {
                   2497:                         my $current = $res->{DATA}->{$valName} || 999999999;
                   2498:                         $res->{DATA}->{$valName} = min($current, $resultingVal + 1);
                   2499:                     }
                   2500:                 }
                   2501:             }
1.96      bowersj2 2502:             
1.107     bowersj2 2503:             # Assign the final val (**2**)
1.97      bowersj2 2504:             if (ref($curRes) && $direction == BACKWARD()) {
1.98      bowersj2 2505:                 my $finalDepth = min($curRes->{DATA}->{TOP_DOWN_VAL},
                   2506:                                      $curRes->{DATA}->{BOT_UP_VAL});
                   2507:                 
                   2508:                 $curRes->{DATA}->{DISPLAY_DEPTH} = $finalDepth;
                   2509:                 if ($finalDepth > $maxDepth) {$maxDepth = $finalDepth;}
1.190     bowersj2 2510:             }
1.222     bowersj2 2511: 
                   2512: 	    $curRes = $iterator->next();
1.96      bowersj2 2513:         }
                   2514:     }
1.94      bowersj2 2515: 
1.116     bowersj2 2516:     # Check: Was this only one resource, a map?
1.255   ! albertel 2517:     if ($resourceCount == 1 && $resource->is_sequence() && !$self->{FORCE_TOP}) { 
1.116     bowersj2 2518:         my $firstResource = $resource->map_start();
                   2519:         my $finishResource = $resource->map_finish();
                   2520:         return 
                   2521:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                   2522:                                               $finishResource, $self->{FILTER},
                   2523:                                               $self->{ALREADY_SEEN}, 
                   2524:                                               $self->{CONDITION}, 0);
                   2525:         
                   2526:     }
                   2527: 
1.98      bowersj2 2528:     # Set up some bookkeeping information.
                   2529:     $self->{CURRENT_DEPTH} = 0;
                   2530:     $self->{MAX_DEPTH} = $maxDepth;
                   2531:     $self->{STACK} = [];
                   2532:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
1.222     bowersj2 2533:     $self->{FINISHED} = 0; # When true, the iterator has finished
1.98      bowersj2 2534: 
                   2535:     for (my $i = 0; $i <= $self->{MAX_DEPTH}; $i++) {
                   2536:         push @{$self->{STACK}}, [];
                   2537:     }
                   2538: 
1.107     bowersj2 2539:     # Prime the recursion w/ the first resource **5**
1.98      bowersj2 2540:     push @{$self->{STACK}->[0]}, $self->{FIRST_RESOURCE};
                   2541:     $self->{ALREADY_SEEN}->{$self->{FIRST_RESOURCE}->{ID}} = 1;
                   2542: 
                   2543:     bless ($self);
                   2544: 
                   2545:     return $self;
                   2546: }
                   2547: 
                   2548: sub next {
                   2549:     my $self = shift;
1.162     bowersj2 2550: 
1.222     bowersj2 2551:     if ($self->{FINISHED}) {
                   2552: 	return END_ITERATOR();
                   2553:     }
                   2554: 
1.162     bowersj2 2555:     # If we want to return the top-level map object, and haven't yet,
                   2556:     # do so.
                   2557:     if ($self->{RETURN_0} && !$self->{HAVE_RETURNED_0}) {
                   2558:         $self->{HAVE_RETURNED_0} = 1;
                   2559:         return $self->{NAV_MAP}->getById('0.0');
                   2560:     }
1.98      bowersj2 2561: 
                   2562:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2563:         # grab the next from the recursive iterator 
                   2564:         my $next = $self->{RECURSIVE_ITERATOR}->next();
                   2565: 
                   2566:         # is it a begin or end map? If so, update the depth
                   2567:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
                   2568:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
                   2569: 
                   2570:         # Are we back at depth 0? If so, stop recursing
                   2571:         if ($self->{RECURSIVE_DEPTH} == 0) {
                   2572:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2573:         }
                   2574: 
                   2575:         return $next;
                   2576:     }
                   2577: 
                   2578:     if (defined($self->{FORCE_NEXT})) {
                   2579:         my $tmp = $self->{FORCE_NEXT};
                   2580:         $self->{FORCE_NEXT} = undef;
                   2581:         return $tmp;
                   2582:     }
                   2583: 
                   2584:     # Have we not yet begun? If not, return BEGIN_MAP and
                   2585:     # remember we've started.
                   2586:     if ( !$self->{STARTED} ) { 
                   2587:         $self->{STARTED} = 1;
                   2588:         return $self->BEGIN_MAP();
                   2589:     }
                   2590: 
                   2591:     # Here's the guts of the iterator.
                   2592:     
                   2593:     # Find the next resource, if any.
                   2594:     my $found = 0;
                   2595:     my $i = $self->{MAX_DEPTH};
                   2596:     my $newDepth;
                   2597:     my $here;
                   2598:     while ( $i >= 0 && !$found ) {
1.107     bowersj2 2599:         if ( scalar(@{$self->{STACK}->[$i]}) > 0 ) { # **6**
                   2600:             $here = pop @{$self->{STACK}->[$i]}; # **7**
1.98      bowersj2 2601:             $found = 1;
                   2602:             $newDepth = $i;
                   2603:         }
                   2604:         $i--;
                   2605:     }
                   2606: 
                   2607:     # If we still didn't find anything, we're done.
                   2608:     if ( !$found ) {
                   2609:         # We need to get back down to the correct branch depth
                   2610:         if ( $self->{CURRENT_DEPTH} > 0 ) {
                   2611:             $self->{CURRENT_DEPTH}--;
                   2612:             return END_BRANCH();
                   2613:         } else {
1.222     bowersj2 2614: 	    $self->{FINISHED} = 1;
1.98      bowersj2 2615:             return END_MAP();
                   2616:         }
                   2617:     }
                   2618: 
1.104     bowersj2 2619:     # If this is not a resource, it must be an END_BRANCH marker we want
                   2620:     # to return directly.
1.107     bowersj2 2621:     if (!ref($here)) { # **8**
1.104     bowersj2 2622:         if ($here == END_BRANCH()) { # paranoia, in case of later extension
                   2623:             $self->{CURRENT_DEPTH}--;
                   2624:             return $here;
                   2625:         }
                   2626:     }
                   2627: 
                   2628:     # Otherwise, it is a resource and it's safe to store in $self->{HERE}
                   2629:     $self->{HERE} = $here;
                   2630: 
1.98      bowersj2 2631:     # Get to the right level
                   2632:     if ( $self->{CURRENT_DEPTH} > $newDepth ) {
                   2633:         push @{$self->{STACK}->[$newDepth]}, $here;
                   2634:         $self->{CURRENT_DEPTH}--;
                   2635:         return END_BRANCH();
                   2636:     }
                   2637:     if ( $self->{CURRENT_DEPTH} < $newDepth) {
                   2638:         push @{$self->{STACK}->[$newDepth]}, $here;
                   2639:         $self->{CURRENT_DEPTH}++;
                   2640:         return BEGIN_BRANCH();
                   2641:     }
                   2642: 
                   2643:     # If we made it here, we have the next resource, and we're at the
                   2644:     # right branch level. So let's examine the resource for where
                   2645:     # we can get to from here.
                   2646: 
                   2647:     # So we need to look at all the resources we can get to from here,
                   2648:     # categorize them if we haven't seen them, remember if we have a new
                   2649:     my $nextUnfiltered = $here->getNext();
1.104     bowersj2 2650:     my $maxDepthAdded = -1;
                   2651:     
1.98      bowersj2 2652:     for (@$nextUnfiltered) {
                   2653:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
1.104     bowersj2 2654:             my $depth = $_->{DATA}->{DISPLAY_DEPTH};
                   2655:             push @{$self->{STACK}->[$depth]}, $_;
1.98      bowersj2 2656:             $self->{ALREADY_SEEN}->{$_->{ID}} = 1;
1.104     bowersj2 2657:             if ($maxDepthAdded < $depth) { $maxDepthAdded = $depth; }
1.98      bowersj2 2658:         }
                   2659:     }
1.104     bowersj2 2660: 
                   2661:     # Is this the end of a branch? If so, all of the resources examined above
                   2662:     # led to lower levels then the one we are currently at, so we push a END_BRANCH
                   2663:     # marker onto the stack so we don't forget.
                   2664:     # Example: For the usual A(BC)(DE)F case, when the iterator goes down the
                   2665:     # BC branch and gets to C, it will see F as the only next resource, but it's
                   2666:     # one level lower. Thus, this is the end of the branch, since there are no
                   2667:     # more resources added to this level or above.
1.111     bowersj2 2668:     # We don't do this if the examined resource is the finish resource,
                   2669:     # because the condition given above is true, but the "END_MAP" will
                   2670:     # take care of things and we should already be at depth 0.
1.104     bowersj2 2671:     my $isEndOfBranch = $maxDepthAdded < $self->{CURRENT_DEPTH};
1.111     bowersj2 2672:     if ($isEndOfBranch && $here != $self->{FINISH_RESOURCE}) { # **9**
1.104     bowersj2 2673:         push @{$self->{STACK}->[$self->{CURRENT_DEPTH}]}, END_BRANCH();
                   2674:     }
                   2675: 
1.98      bowersj2 2676:     # That ends the main iterator logic. Now, do we want to recurse
                   2677:     # down this map (if this resource is a map)?
                   2678:     if ($self->{HERE}->is_map() &&
                   2679:         (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) {
                   2680:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
                   2681:         my $firstResource = $self->{HERE}->map_start();
                   2682:         my $finishResource = $self->{HERE}->map_finish();
                   2683: 
                   2684:         $self->{RECURSIVE_ITERATOR} = 
                   2685:             Apache::lonnavmaps::iterator->new($self->{NAV_MAP}, $firstResource,
                   2686:                                               $finishResource, $self->{FILTER},
                   2687:                                               $self->{ALREADY_SEEN}, $self->{CONDITION});
                   2688:     }
                   2689: 
1.116     bowersj2 2690:     # If this is a blank resource, don't actually return it.
1.117     bowersj2 2691:     # Should you ever find you need it, make sure to add an option to the code
                   2692:     #  that you can use; other things depend on this behavior.
1.138     bowersj2 2693:     my $browsePriv = $self->{HERE}->browsePriv();
                   2694:     if (!$self->{HERE}->src() || 
                   2695:         (!($browsePriv eq 'F') && !($browsePriv eq '2')) ) {
1.116     bowersj2 2696:         return $self->next();
                   2697:     }
                   2698: 
1.98      bowersj2 2699:     return $self->{HERE};
                   2700: 
                   2701: }
                   2702: 
                   2703: =pod
                   2704: 
1.174     albertel 2705: The other method available on the iterator is B<getStack>, which
                   2706: returns an array populated with the current 'stack' of maps, as
                   2707: references to the resource objects. Example: This is useful when
                   2708: making the navigation map, as we need to check whether we are under a
                   2709: page map to see if we need to link directly to the resource, or to the
                   2710: page. The first elements in the array will correspond to the top of
                   2711: the stack (most inclusive map).
1.98      bowersj2 2712: 
                   2713: =cut
                   2714: 
                   2715: sub getStack {
                   2716:     my $self=shift;
                   2717: 
                   2718:     my @stack;
                   2719: 
                   2720:     $self->populateStack(\@stack);
                   2721: 
                   2722:     return \@stack;
                   2723: }
                   2724: 
                   2725: # Private method: Calls the iterators recursively to populate the stack.
                   2726: sub populateStack {
                   2727:     my $self=shift;
                   2728:     my $stack = shift;
                   2729: 
                   2730:     push @$stack, $self->{HERE} if ($self->{HERE});
                   2731: 
                   2732:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2733:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
                   2734:     }
1.94      bowersj2 2735: }
                   2736: 
                   2737: 1;
                   2738: 
                   2739: package Apache::lonnavmaps::DFSiterator;
                   2740: 
1.100     bowersj2 2741: # Not documented in the perldoc: This is a simple iterator that just walks
                   2742: #  through the nav map and presents the resources in a depth-first search
                   2743: #  fashion, ignorant of conditionals, randomized resources, etc. It presents
                   2744: #  BEGIN_MAP and END_MAP, but does not understand branches at all. It is
                   2745: #  useful for pre-processing of some kind, and is in fact used by the main
                   2746: #  iterator that way, but that's about it.
                   2747: # One could imagine merging this into the init routine of the main iterator,
1.251     www      2748: #  but this might as well be left separate, since it is possible some other
1.100     bowersj2 2749: #  use might be found for it. - Jeremy
1.94      bowersj2 2750: 
1.117     bowersj2 2751: # Unlike the main iterator, this DOES return all resources, even blank ones.
                   2752: #  The main iterator needs them to correctly preprocess the map.
                   2753: 
1.94      bowersj2 2754: sub BEGIN_MAP { return 1; }    # begining of a new map
                   2755: sub END_MAP { return 2; }      # end of the map
                   2756: sub FORWARD { return 1; }      # go forward
                   2757: sub BACKWARD { return 2; }
                   2758: 
1.100     bowersj2 2759: # Params: Nav map ref, first resource id/ref, finish resource id/ref,
                   2760: #         filter hash ref (or undef), already seen hash or undef, condition
                   2761: #         (as in main iterator), direction FORWARD or BACKWARD (undef->forward).
1.51      bowersj2 2762: sub new {
                   2763:     # magic invocation to create a class instance
                   2764:     my $proto = shift;
                   2765:     my $class = ref($proto) || $proto;
                   2766:     my $self = {};
                   2767: 
                   2768:     $self->{NAV_MAP} = shift;
                   2769:     return undef unless ($self->{NAV_MAP});
                   2770: 
                   2771:     $self->{FIRST_RESOURCE} = shift || $self->{NAV_MAP}->firstResource();
                   2772:     $self->{FINISH_RESOURCE} = shift || $self->{NAV_MAP}->finishResource();
                   2773: 
                   2774:     # If the given resources are just the ID of the resource, get the
                   2775:     # objects
                   2776:     if (!ref($self->{FIRST_RESOURCE})) { $self->{FIRST_RESOURCE} = 
                   2777:              $self->{NAV_MAP}->getById($self->{FIRST_RESOURCE}); }
                   2778:     if (!ref($self->{FINISH_RESOURCE})) { $self->{FINISH_RESOURCE} = 
                   2779:              $self->{NAV_MAP}->getById($self->{FINISH_RESOURCE}); }
                   2780: 
                   2781:     $self->{FILTER} = shift;
                   2782: 
                   2783:     # A hash, used as a set, of resource already seen
                   2784:     $self->{ALREADY_SEEN} = shift;
1.140     bowersj2 2785:      if (!defined($self->{ALREADY_SEEN})) { $self->{ALREADY_SEEN} = {} };
1.63      bowersj2 2786:     $self->{CONDITION} = shift;
1.89      bowersj2 2787:     $self->{DIRECTION} = shift || FORWARD();
1.51      bowersj2 2788: 
1.100     bowersj2 2789:     # Flag: Have we started yet?
1.51      bowersj2 2790:     $self->{STARTED} = 0;
                   2791: 
                   2792:     # Should we continue calling the recursive iterator, if any?
                   2793:     $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2794:     # The recursive iterator, if any
                   2795:     $self->{RECURSIVE_ITERATOR} = undef;
                   2796:     # Are we recursing on a map, or a branch?
                   2797:     $self->{RECURSIVE_MAP} = 1; # we'll manually unset this when recursing on branches
                   2798:     # And the count of how deep it is, so that this iterator can keep track of
                   2799:     # when to pick back up again.
                   2800:     $self->{RECURSIVE_DEPTH} = 0;
                   2801: 
                   2802:     # For keeping track of our branches, we maintain our own stack
1.100     bowersj2 2803:     $self->{STACK} = [];
1.51      bowersj2 2804: 
                   2805:     # Start with the first resource
1.89      bowersj2 2806:     if ($self->{DIRECTION} == FORWARD) {
1.100     bowersj2 2807:         push @{$self->{STACK}}, $self->{FIRST_RESOURCE};
1.89      bowersj2 2808:     } else {
1.100     bowersj2 2809:         push @{$self->{STACK}}, $self->{FINISH_RESOURCE};
1.89      bowersj2 2810:     }
1.51      bowersj2 2811: 
                   2812:     bless($self);
                   2813:     return $self;
                   2814: }
                   2815: 
                   2816: sub next {
                   2817:     my $self = shift;
                   2818:     
                   2819:     # Are we using a recursive iterator? If so, pull from that and
                   2820:     # watch the depth; we want to resume our level at the correct time.
1.98      bowersj2 2821:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
1.51      bowersj2 2822:         # grab the next from the recursive iterator
                   2823:         my $next = $self->{RECURSIVE_ITERATOR}->next();
                   2824:         
                   2825:         # is it a begin or end map? Update depth if so
                   2826:         if ($next == BEGIN_MAP() ) { $self->{RECURSIVE_DEPTH}++; }
                   2827:         if ($next == END_MAP() ) { $self->{RECURSIVE_DEPTH}--; }
                   2828: 
                   2829:         # Are we back at depth 0? If so, stop recursing.
                   2830:         if ($self->{RECURSIVE_DEPTH} == 0) {
                   2831:             $self->{RECURSIVE_ITERATOR_FLAG} = 0;
                   2832:         }
                   2833:         
                   2834:         return $next;
                   2835:     }
                   2836: 
                   2837:     # Is there a current resource to grab? If not, then return
1.100     bowersj2 2838:     # END_MAP, which will end the iterator.
                   2839:     if (scalar(@{$self->{STACK}}) == 0) {
                   2840:         return $self->END_MAP();
1.51      bowersj2 2841:     }
                   2842: 
                   2843:     # Have we not yet begun? If not, return BEGIN_MAP and 
                   2844:     # remember that we've started.
                   2845:     if ( !$self->{STARTED} ) {
                   2846:         $self->{STARTED} = 1;
                   2847:         return $self->BEGIN_MAP;
                   2848:     }
                   2849: 
                   2850:     # Get the next resource in the branch
1.100     bowersj2 2851:     $self->{HERE} = pop @{$self->{STACK}};
1.52      bowersj2 2852: 
1.100     bowersj2 2853:     # remember that we've seen this, so we don't return it again later
1.51      bowersj2 2854:     $self->{ALREADY_SEEN}->{$self->{HERE}->{ID}} = 1;
                   2855:     
                   2856:     # Get the next possible resources
1.90      bowersj2 2857:     my $nextUnfiltered;
1.89      bowersj2 2858:     if ($self->{DIRECTION} == FORWARD()) {
1.90      bowersj2 2859:         $nextUnfiltered = $self->{HERE}->getNext();
1.89      bowersj2 2860:     } else {
1.90      bowersj2 2861:         $nextUnfiltered = $self->{HERE}->getPrevious();
1.89      bowersj2 2862:     }
1.51      bowersj2 2863:     my $next = [];
                   2864: 
                   2865:     # filter the next possibilities to remove things we've 
1.100     bowersj2 2866:     # already seen.
1.51      bowersj2 2867:     foreach (@$nextUnfiltered) {
1.52      bowersj2 2868:         if (!defined($self->{ALREADY_SEEN}->{$_->{ID}})) {
                   2869:             push @$next, $_;
                   2870:         }
1.51      bowersj2 2871:     }
                   2872: 
                   2873:     while (@$next) {
1.100     bowersj2 2874:         # copy the next possibilities over to the stack
                   2875:         push @{$self->{STACK}}, shift @$next;
1.51      bowersj2 2876:     }
                   2877: 
                   2878:     # If this is a map and we want to recurse down it... (not filtered out)
1.70      bowersj2 2879:     if ($self->{HERE}->is_map() && 
1.63      bowersj2 2880:          (defined($self->{FILTER}->{$self->{HERE}->map_pc()}) xor $self->{CONDITION})) { 
1.51      bowersj2 2881:         $self->{RECURSIVE_ITERATOR_FLAG} = 1;
                   2882:         my $firstResource = $self->{HERE}->map_start();
                   2883:         my $finishResource = $self->{HERE}->map_finish();
                   2884: 
                   2885:         $self->{RECURSIVE_ITERATOR} =
1.94      bowersj2 2886:           Apache::lonnavmaps::DFSiterator->new ($self->{NAV_MAP}, $firstResource, 
1.63      bowersj2 2887:                      $finishResource, $self->{FILTER}, $self->{ALREADY_SEEN},
1.91      bowersj2 2888:                                              $self->{CONDITION}, $self->{DIRECTION});
1.51      bowersj2 2889:     }
                   2890: 
                   2891:     return $self->{HERE};
1.190     bowersj2 2892: }
                   2893: 
                   2894: # Identical to the full iterator methods of the same name. Hate to copy/paste
                   2895: # but I also hate to "inherit" either iterator from the other.
                   2896: 
                   2897: sub getStack {
                   2898:     my $self=shift;
                   2899: 
                   2900:     my @stack;
                   2901: 
                   2902:     $self->populateStack(\@stack);
                   2903: 
                   2904:     return \@stack;
                   2905: }
                   2906: 
                   2907: # Private method: Calls the iterators recursively to populate the stack.
                   2908: sub populateStack {
                   2909:     my $self=shift;
                   2910:     my $stack = shift;
                   2911: 
                   2912:     push @$stack, $self->{HERE} if ($self->{HERE});
                   2913: 
                   2914:     if ($self->{RECURSIVE_ITERATOR_FLAG}) {
                   2915:         $self->{RECURSIVE_ITERATOR}->populateStack($stack);
                   2916:     }
1.51      bowersj2 2917: }
                   2918: 
1.1       www      2919: 1;
1.2       www      2920: 
1.51      bowersj2 2921: package Apache::lonnavmaps::resource;
                   2922: 
                   2923: use Apache::lonnet;
                   2924: 
                   2925: =pod
                   2926: 
1.217     bowersj2 2927: =head1 Object: resource 
1.51      bowersj2 2928: 
1.217     bowersj2 2929: X<resource, navmap object>
1.174     albertel 2930: A resource object encapsulates a resource in a resource map, allowing
                   2931: easy manipulation of the resource, querying the properties of the
                   2932: resource (including user properties), and represents a reference that
                   2933: can be used as the canonical representation of the resource by
                   2934: lonnavmap clients like renderers.
                   2935: 
                   2936: A resource only makes sense in the context of a navmap, as some of the
                   2937: data is stored in the navmap object.
                   2938: 
                   2939: You will probably never need to instantiate this object directly. Use
                   2940: Apache::lonnavmaps::navmap, and use the "start" method to obtain the
                   2941: starting resource.
1.51      bowersj2 2942: 
1.188     bowersj2 2943: Resource objects respect the parameter_hiddenparts, which suppresses 
                   2944: various parts according to the wishes of the map author. As of this
                   2945: writing, there is no way to override this parameter, and suppressed
                   2946: parts will never be returned, nor will their response types or ids be
                   2947: stored.
                   2948: 
1.217     bowersj2 2949: =head2 Overview
1.51      bowersj2 2950: 
1.217     bowersj2 2951: A B<Resource> is the most granular type of object in LON-CAPA that can
                   2952: be included in a course. It can either be a particular resource, like
                   2953: an HTML page, external resource, problem, etc., or it can be a
                   2954: container sequence, such as a "page" or a "map".
                   2955: 
                   2956: To see a sequence from the user's point of view, please see the
                   2957: B<Creating a Course: Maps and Sequences> chapter of the Author's
                   2958: Manual.
                   2959: 
                   2960: A Resource Object, once obtained from a navmap object via a B<getBy*>
                   2961: method of the navmap, or from an iterator, allows you to query
                   2962: information about that resource.
                   2963: 
                   2964: Generally, you do not ever want to create a resource object yourself,
                   2965: so creation has been left undocumented. Always retrieve resources
                   2966: from navmap objects.
                   2967: 
                   2968: =head3 Identifying Resources
                   2969: 
                   2970: X<big hash>Every resource is identified by a Resource ID in the big hash that is
                   2971: unique to that resource for a given course. X<resource ID, in big hash>
                   2972: The Resource ID has the form #.#, where the first number is the same
                   2973: for every resource in a map, and the second is unique. For instance,
                   2974: for a course laid out like this:
                   2975: 
                   2976:  * Problem 1
                   2977:  * Map
                   2978:    * Resource 2
                   2979:    * Resource 3
                   2980: 
                   2981: C<Problem 1> and C<Map> will share a first number, and C<Resource 2>
                   2982: C<Resource 3> will share a first number. The second number may end up
                   2983: re-used between the two groups.
                   2984: 
                   2985: The resource ID is only used in the big hash, but can be used in the
                   2986: context of a course to identify a resource easily. (For instance, the
                   2987: printing system uses it to record which resources from a sequence you 
                   2988: wish to print.)
                   2989: 
                   2990: X<symb> X<resource, symb>
                   2991: All resources also have B<symb>s, which uniquely identify a resource
                   2992: in a course. Many internal LON-CAPA functions expect a symb. A symb
                   2993: carries along with it the URL of the resource, and the map it appears
                   2994: in. Symbs are much larger then resource IDs.
1.51      bowersj2 2995: 
                   2996: =cut
                   2997: 
                   2998: sub new {
                   2999:     # magic invocation to create a class instance
                   3000:     my $proto = shift;
                   3001:     my $class = ref($proto) || $proto;
                   3002:     my $self = {};
                   3003: 
                   3004:     $self->{NAV_MAP} = shift;
                   3005:     $self->{ID} = shift;
                   3006: 
                   3007:     # Store this new resource in the parent nav map's cache.
                   3008:     $self->{NAV_MAP}->{RESOURCE_CACHE}->{$self->{ID}} = $self;
1.66      bowersj2 3009:     $self->{RESOURCE_ERROR} = 0;
1.51      bowersj2 3010: 
                   3011:     # A hash that can be used by two-pass algorithms to store data
                   3012:     # about this resource in. Not used by the resource object
                   3013:     # directly.
                   3014:     $self->{DATA} = {};
                   3015:    
                   3016:     bless($self);
                   3017:     
                   3018:     return $self;
                   3019: }
                   3020: 
1.70      bowersj2 3021: # private function: simplify the NAV_HASH lookups we keep doing
                   3022: # pass the name, and to automatically append my ID, pass a true val on the
                   3023: # second param
                   3024: sub navHash {
                   3025:     my $self = shift;
                   3026:     my $param = shift;
                   3027:     my $id = shift;
1.115     bowersj2 3028:     return $self->{NAV_MAP}->navhash($param . ($id?$self->{ID}:""));
1.70      bowersj2 3029: }
                   3030: 
1.51      bowersj2 3031: =pod
                   3032: 
1.217     bowersj2 3033: =head2 Methods
1.70      bowersj2 3034: 
1.217     bowersj2 3035: Once you have a resource object, here's what you can do with it:
                   3036: 
                   3037: =head3 Attribute Retrieval
                   3038: 
                   3039: Every resource has certain attributes that can be retrieved and used:
1.70      bowersj2 3040: 
                   3041: =over 4
                   3042: 
1.217     bowersj2 3043: =item * B<ID>: Every resource has an ID that is unique for that
                   3044:     resource in the course it is in. The ID is actually in the hash
                   3045:     representing the resource, so for a resource object $res, obtain
                   3046:     it via C<$res->{ID}).
                   3047: 
1.174     albertel 3048: =item * B<compTitle>:
                   3049: 
                   3050: Returns a "composite title", that is equal to $res->title() if the
                   3051: resource has a title, and is otherwise the last part of the URL (e.g.,
                   3052: "problem.problem").
                   3053: 
                   3054: =item * B<ext>:
                   3055: 
                   3056: Returns true if the resource is external.
                   3057: 
                   3058: =item * B<kind>:
                   3059: 
                   3060: Returns the kind of the resource from the compiled nav map.
                   3061: 
                   3062: =item * B<randomout>:
1.106     bowersj2 3063: 
1.174     albertel 3064: Returns true if this resource was chosen to NOT be shown to the user
                   3065: by the random map selection feature. In other words, this is usually
                   3066: false.
1.70      bowersj2 3067: 
1.174     albertel 3068: =item * B<randompick>:
1.70      bowersj2 3069: 
1.174     albertel 3070: Returns true for a map if the randompick feature is being used on the
                   3071: map. (?)
1.70      bowersj2 3072: 
1.174     albertel 3073: =item * B<src>:
1.51      bowersj2 3074: 
1.174     albertel 3075: Returns the source for the resource.
1.70      bowersj2 3076: 
1.174     albertel 3077: =item * B<symb>:
1.70      bowersj2 3078: 
1.174     albertel 3079: Returns the symb for the resource.
1.70      bowersj2 3080: 
1.174     albertel 3081: =item * B<title>:
1.70      bowersj2 3082: 
1.174     albertel 3083: Returns the title of the resource.
                   3084: 
1.51      bowersj2 3085: =back
                   3086: 
                   3087: =cut
                   3088: 
                   3089: # These info functions can be used directly, as they don't return
                   3090: # resource information.
1.85      bowersj2 3091: sub comesfrom { my $self=shift; return $self->navHash("comesfrom_", 1); }
1.70      bowersj2 3092: sub ext { my $self=shift; return $self->navHash("ext_", 1) eq 'true:'; }
1.85      bowersj2 3093: sub from { my $self=shift; return $self->navHash("from_", 1); }
1.217     bowersj2 3094: # considered private and undocumented
1.51      bowersj2 3095: sub goesto { my $self=shift; return $self->navHash("goesto_", 1); }
                   3096: sub kind { my $self=shift; return $self->navHash("kind_", 1); }
1.68      bowersj2 3097: sub randomout { my $self=shift; return $self->navHash("randomout_", 1); }
                   3098: sub randompick { 
                   3099:     my $self = shift;
                   3100:     return $self->{NAV_MAP}->{PARM_HASH}->{$self->symb .
                   3101:                                                '.0.parameter_randompick'};
                   3102: }
1.51      bowersj2 3103: sub src { 
                   3104:     my $self=shift;
                   3105:     return $self->navHash("src_", 1);
                   3106: }
                   3107: sub symb {
                   3108:     my $self=shift;
                   3109:     (my $first, my $second) = $self->{ID} =~ /(\d+).(\d+)/;
                   3110:     my $symbSrc = &Apache::lonnet::declutter($self->src());
1.223     albertel 3111:     my $symb = &Apache::lonnet::declutter($self->navHash('map_id_'.$first)) 
1.51      bowersj2 3112:         . '___' . $second . '___' . $symbSrc;
1.223     albertel 3113:     return &Apache::lonnet::symbclean($symb);
1.51      bowersj2 3114: }
1.213     bowersj2 3115: sub title { 
                   3116:     my $self=shift; 
                   3117:     if ($self->{ID} eq '0.0') {
                   3118: 	# If this is the top-level map, return the title of the course
                   3119: 	# since this map can not be titled otherwise.
                   3120: 	return $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
                   3121:     }
                   3122:     return $self->navHash("title_", 1); }
1.217     bowersj2 3123: # considered private and undocumented
1.70      bowersj2 3124: sub to { my $self=shift; return $self->navHash("to_", 1); }
1.106     bowersj2 3125: sub compTitle {
                   3126:     my $self = shift;
                   3127:     my $title = $self->title();
1.176     www      3128:     $title=~s/\&colon\;/\:/gs;
1.106     bowersj2 3129:     if (!$title) {
                   3130:         $title = $self->src();
                   3131:         $title = substr($title, rindex($title, '/') + 1);
                   3132:     }
                   3133:     return $title;
                   3134: }
1.70      bowersj2 3135: =pod
                   3136: 
                   3137: B<Predicate Testing the Resource>
                   3138: 
                   3139: These methods are shortcuts to deciding if a given resource has a given property.
                   3140: 
                   3141: =over 4
                   3142: 
1.174     albertel 3143: =item * B<is_map>:
                   3144: 
                   3145: Returns true if the resource is a map type.
                   3146: 
                   3147: =item * B<is_problem>:
1.70      bowersj2 3148: 
1.174     albertel 3149: Returns true if the resource is a problem type, false
                   3150: otherwise. (Looks at the extension on the src field; might need more
                   3151: to work correctly.)
1.70      bowersj2 3152: 
1.174     albertel 3153: =item * B<is_page>:
1.70      bowersj2 3154: 
1.174     albertel 3155: Returns true if the resource is a page.
                   3156: 
                   3157: =item * B<is_sequence>:
                   3158: 
                   3159: Returns true if the resource is a sequence.
1.70      bowersj2 3160: 
                   3161: =back
                   3162: 
                   3163: =cut
                   3164: 
                   3165: 
                   3166: sub is_html {
1.51      bowersj2 3167:     my $self=shift;
                   3168:     my $src = $self->src();
1.70      bowersj2 3169:     return ($src =~ /html$/);
1.51      bowersj2 3170: }
1.70      bowersj2 3171: sub is_map { my $self=shift; return defined($self->navHash("is_map_", 1)); }
                   3172: sub is_page {
1.51      bowersj2 3173:     my $self=shift;
                   3174:     my $src = $self->src();
1.205     bowersj2 3175:     return $self->navHash("is_map_", 1) && 
                   3176: 	$self->navHash("map_type_" . $self->map_pc()) eq 'page';
1.51      bowersj2 3177: }
1.70      bowersj2 3178: sub is_problem {
1.51      bowersj2 3179:     my $self=shift;
                   3180:     my $src = $self->src();
1.250     albertel 3181:     return ($src =~ /\.(problem|exam|quiz|assess|survey|form|library)$/);
1.51      bowersj2 3182: }
1.70      bowersj2 3183: sub is_sequence {
1.51      bowersj2 3184:     my $self=shift;
                   3185:     my $src = $self->src();
1.205     bowersj2 3186:     return $self->navHash("is_map_", 1) && 
                   3187: 	$self->navHash("map_type_" . $self->map_pc()) eq 'sequence';
1.51      bowersj2 3188: }
                   3189: 
1.101     bowersj2 3190: # Private method: Shells out to the parmval in the nav map, handler parts.
1.51      bowersj2 3191: sub parmval {
                   3192:     my $self = shift;
                   3193:     my $what = shift;
1.185     bowersj2 3194:     my $part = shift;
                   3195:     if (!defined($part)) { 
                   3196:         $part = '0'; 
                   3197:     }
1.51      bowersj2 3198:     return $self->{NAV_MAP}->parmval($part.'.'.$what, $self->symb());
                   3199: }
                   3200: 
1.70      bowersj2 3201: =pod
                   3202: 
                   3203: B<Map Methods>
                   3204: 
1.174     albertel 3205: These methods are useful for getting information about the map
                   3206: properties of the resource, if the resource is a map (B<is_map>).
1.70      bowersj2 3207: 
                   3208: =over 4
                   3209: 
1.174     albertel 3210: =item * B<map_finish>:
                   3211: 
                   3212: Returns a reference to a resource object corresponding to the finish
                   3213: resource of the map.
1.70      bowersj2 3214: 
1.174     albertel 3215: =item * B<map_pc>:
1.70      bowersj2 3216: 
1.174     albertel 3217: Returns the pc value of the map, which is the first number that
                   3218: appears in the resource ID of the resources in the map, and is the
                   3219: number that appears around the middle of the symbs of the resources in
                   3220: that map.
1.70      bowersj2 3221: 
1.174     albertel 3222: =item * B<map_start>:
                   3223: 
                   3224: Returns a reference to a resource object corresponding to the start
                   3225: resource of the map.
                   3226: 
                   3227: =item * B<map_type>:
                   3228: 
                   3229: Returns a string with the type of the map in it.
1.70      bowersj2 3230: 
                   3231: =back
1.51      bowersj2 3232: 
1.70      bowersj2 3233: =cut
1.51      bowersj2 3234: 
                   3235: sub map_finish {
                   3236:     my $self = shift;
                   3237:     my $src = $self->src();
1.144     bowersj2 3238:     $src = Apache::lonnet::clutter($src);
1.51      bowersj2 3239:     my $res = $self->navHash("map_finish_$src", 0);
                   3240:     $res = $self->{NAV_MAP}->getById($res);
                   3241:     return $res;
                   3242: }
1.70      bowersj2 3243: sub map_pc {
                   3244:     my $self = shift;
                   3245:     my $src = $self->src();
                   3246:     return $self->navHash("map_pc_$src", 0);
                   3247: }
1.51      bowersj2 3248: sub map_start {
                   3249:     my $self = shift;
                   3250:     my $src = $self->src();
1.144     bowersj2 3251:     $src = Apache::lonnet::clutter($src);
1.51      bowersj2 3252:     my $res = $self->navHash("map_start_$src", 0);
                   3253:     $res = $self->{NAV_MAP}->getById($res);
                   3254:     return $res;
                   3255: }
                   3256: sub map_type {
                   3257:     my $self = shift;
                   3258:     my $pc = $self->map_pc();
                   3259:     return $self->navHash("map_type_$pc", 0);
                   3260: }
                   3261: 
                   3262: #####
                   3263: # Property queries
                   3264: #####
                   3265: 
                   3266: # These functions will be responsible for returning the CORRECT
                   3267: # VALUE for the parameter, no matter what. So while they may look
                   3268: # like direct calls to parmval, they can be more then that.
                   3269: # So, for instance, the duedate function should use the "duedatetype"
                   3270: # information, rather then the resource object user.
                   3271: 
                   3272: =pod
                   3273: 
                   3274: =head2 Resource Parameters
                   3275: 
1.174     albertel 3276: In order to use the resource parameters correctly, the nav map must
                   3277: have been instantiated with genCourseAndUserOptions set to true, so
                   3278: the courseopt and useropt is read correctly. Then, you can call these
                   3279: functions to get the relevant parameters for the resource. Each
                   3280: function defaults to part "0", but can be directed to another part by
                   3281: passing the part as the parameter.
                   3282: 
                   3283: These methods are responsible for getting the parameter correct, not
                   3284: merely reflecting the contents of the GDBM hashes. As we move towards
                   3285: dates relative to other dates, these methods should be updated to
                   3286: reflect that. (Then, anybody using these methods will not have to update
                   3287: their code.)
                   3288: 
                   3289: =over 4
                   3290: 
                   3291: =item * B<acc>:
                   3292: 
                   3293: Get the Client IP/Name Access Control information.
1.51      bowersj2 3294: 
1.174     albertel 3295: =item * B<answerdate>:
1.51      bowersj2 3296: 
1.174     albertel 3297: Get the answer-reveal date for the problem.
                   3298: 
1.211     bowersj2 3299: =item * B<awarded>: 
                   3300: 
                   3301: Gets the awarded value for the problem part. Requires genUserData set to
                   3302: true when the navmap object was created.
                   3303: 
1.174     albertel 3304: =item * B<duedate>:
                   3305: 
                   3306: Get the due date for the problem.
                   3307: 
                   3308: =item * B<tries>:
                   3309: 
                   3310: Get the number of tries the student has used on the problem.
                   3311: 
                   3312: =item * B<maxtries>:
                   3313: 
                   3314: Get the number of max tries allowed.
                   3315: 
                   3316: =item * B<opendate>:
1.51      bowersj2 3317: 
1.174     albertel 3318: Get the open date for the problem.
1.51      bowersj2 3319: 
1.174     albertel 3320: =item * B<sig>:
1.51      bowersj2 3321: 
1.174     albertel 3322: Get the significant figures setting.
1.51      bowersj2 3323: 
1.174     albertel 3324: =item * B<tol>:
1.51      bowersj2 3325: 
1.174     albertel 3326: Get the tolerance for the problem.
1.51      bowersj2 3327: 
1.174     albertel 3328: =item * B<tries>:
1.51      bowersj2 3329: 
1.174     albertel 3330: Get the number of tries the user has already used on the problem.
1.51      bowersj2 3331: 
1.174     albertel 3332: =item * B<type>:
1.51      bowersj2 3333: 
1.174     albertel 3334: Get the question type for the problem.
1.70      bowersj2 3335: 
1.174     albertel 3336: =item * B<weight>:
1.51      bowersj2 3337: 
1.174     albertel 3338: Get the weight for the problem.
1.51      bowersj2 3339: 
                   3340: =back
                   3341: 
                   3342: =cut
                   3343: 
                   3344: sub acc {
                   3345:     (my $self, my $part) = @_;
                   3346:     return $self->parmval("acc", $part);
                   3347: }
                   3348: sub answerdate {
                   3349:     (my $self, my $part) = @_;
                   3350:     # Handle intervals
                   3351:     if ($self->parmval("answerdate.type", $part) eq 'date_interval') {
                   3352:         return $self->duedate($part) + 
                   3353:             $self->parmval("answerdate", $part);
                   3354:     }
                   3355:     return $self->parmval("answerdate", $part);
1.106     bowersj2 3356: }
1.211     bowersj2 3357: sub awarded { 
                   3358:     my $self = shift; my $part = shift;
1.221     bowersj2 3359:     $self->{NAV_MAP}->get_user_data();
1.211     bowersj2 3360:     if (!defined($part)) { $part = '0'; }
                   3361:     return $self->{NAV_MAP}->{STUDENT_DATA}->{$self->symb()}->{'resource.'.$part.'.awarded'};
                   3362: }
1.51      bowersj2 3363: sub duedate {
                   3364:     (my $self, my $part) = @_;
                   3365:     return $self->parmval("duedate", $part);
                   3366: }
                   3367: sub maxtries {
                   3368:     (my $self, my $part) = @_;
                   3369:     return $self->parmval("maxtries", $part);
                   3370: }
                   3371: sub opendate {
                   3372:     (my $self, my $part) = @_;
                   3373:     if ($self->parmval("opendate.type", $part) eq 'date_interval') {
                   3374:         return $self->duedate($part) -
                   3375:             $self->parmval("opendate", $part);
                   3376:     }
                   3377:     return $self->parmval("opendate");
                   3378: }
1.185     bowersj2 3379: sub problemstatus {
                   3380:     (my $self, my $part) = @_;
1.236     bowersj2 3381:     return lc $self->parmval("problemstatus", $part);
1.185     bowersj2 3382: }
1.51      bowersj2 3383: sub sig {
                   3384:     (my $self, my $part) = @_;
                   3385:     return $self->parmval("sig", $part);
                   3386: }
                   3387: sub tol {
                   3388:     (my $self, my $part) = @_;
                   3389:     return $self->parmval("tol", $part);
                   3390: }
1.108     bowersj2 3391: sub tries { 
                   3392:     my $self = shift; 
                   3393:     my $tries = $self->queryRestoreHash('tries', shift);
                   3394:     if (!defined($tries)) { return '0';}
1.51      bowersj2 3395:     return $tries;
                   3396: }
1.70      bowersj2 3397: sub type {
                   3398:     (my $self, my $part) = @_;
                   3399:     return $self->parmval("type", $part);
                   3400: }
1.109     bowersj2 3401: sub weight { 
                   3402:     my $self = shift; my $part = shift;
1.211     bowersj2 3403:     if (!defined($part)) { $part = '0'; }
                   3404:     return &Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3405: 				$self->symb(), $ENV{'user.domain'},
                   3406: 				$ENV{'user.name'}, 
                   3407: 				$ENV{'request.course.sec'});
                   3408: 
1.70      bowersj2 3409: }
1.51      bowersj2 3410: 
                   3411: # Multiple things need this
                   3412: sub getReturnHash {
                   3413:     my $self = shift;
                   3414:     
                   3415:     if (!defined($self->{RETURN_HASH})) {
1.84      bowersj2 3416:         my %tmpHash  = &Apache::lonnet::restore($self->symb());
1.51      bowersj2 3417:         $self->{RETURN_HASH} = \%tmpHash;
                   3418:     }
                   3419: }       
                   3420: 
                   3421: ######
                   3422: # Status queries
                   3423: ######
                   3424: 
                   3425: # These methods query the status of problems.
                   3426: 
                   3427: # If we need to count parts, this function determines the number of
                   3428: # parts from the metadata. When called, it returns a reference to a list
                   3429: # of strings corresponding to the parts. (Thus, using it in a scalar context
                   3430: # tells you how many parts you have in the problem:
                   3431: # $partcount = scalar($resource->countParts());
                   3432: # Don't use $self->{PARTS} directly because you don't know if it's been
                   3433: # computed yet.
                   3434: 
                   3435: =pod
                   3436: 
                   3437: =head2 Resource misc
                   3438: 
                   3439: Misc. functions for the resource.
                   3440: 
                   3441: =over 4
                   3442: 
1.174     albertel 3443: =item * B<hasDiscussion>:
1.59      bowersj2 3444: 
1.174     albertel 3445: Returns a false value if there has been discussion since the user last
                   3446: logged in, true if there has. Always returns false if the discussion
                   3447: data was not extracted when the nav map was constructed.
                   3448: 
                   3449: =item * B<getFeedback>:
                   3450: 
                   3451: Gets the feedback for the resource and returns the raw feedback string
                   3452: for the resource, or the null string if there is no feedback or the
                   3453: email data was not extracted when the nav map was constructed. Usually
                   3454: used like this:
1.59      bowersj2 3455: 
                   3456:  for (split(/\,/, $res->getFeedback())) {
                   3457:     my $link = &Apache::lonnet::escape($_);
                   3458:     ...
                   3459: 
                   3460: and use the link as appropriate.
                   3461: 
                   3462: =cut
                   3463: 
                   3464: sub hasDiscussion {
                   3465:     my $self = shift;
                   3466:     return $self->{NAV_MAP}->hasDiscussion($self->symb());
                   3467: }
                   3468: 
                   3469: sub getFeedback {
                   3470:     my $self = shift;
1.124     bowersj2 3471:     my $source = $self->src();
1.125     bowersj2 3472:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
1.124     bowersj2 3473:     return $self->{NAV_MAP}->getFeedback($source);
                   3474: }
                   3475: 
                   3476: sub getErrors {
                   3477:     my $self = shift;
                   3478:     my $source = $self->src();
                   3479:     if ($source =~ /^\/res\//) { $source = substr $source, 5; }
                   3480:     return $self->{NAV_MAP}->getErrors($source);
1.59      bowersj2 3481: }
                   3482: 
                   3483: =pod
                   3484: 
1.174     albertel 3485: =item * B<parts>():
1.51      bowersj2 3486: 
1.174     albertel 3487: Returns a list reference containing sorted strings corresponding to
1.193     bowersj2 3488: each part of the problem. Single part problems have only a part '0'.
                   3489: Multipart problems do not return their part '0', since they typically
                   3490: do not really matter. 
1.174     albertel 3491: 
                   3492: =item * B<countParts>():
                   3493: 
                   3494: Returns the number of parts of the problem a student can answer. Thus,
                   3495: for single part problems, returns 1. For multipart, it returns the
1.193     bowersj2 3496: number of parts in the problem, not including psuedo-part 0. 
1.51      bowersj2 3497: 
1.192     bowersj2 3498: =item * B<multipart>():
                   3499: 
1.193     bowersj2 3500: Returns true if the problem is multipart, false otherwise. Use this instead
                   3501: of countParts if all you want is multipart/not multipart.
1.192     bowersj2 3502: 
1.187     bowersj2 3503: =item * B<responseType>($part):
                   3504: 
                   3505: Returns the response type of the part, without the word "response" on the
                   3506: end. Example return values: 'string', 'essay', 'numeric', etc.
                   3507: 
1.193     bowersj2 3508: =item * B<responseIds>($part):
1.187     bowersj2 3509: 
1.193     bowersj2 3510: Retreives the response IDs for the given part as an array reference containing
                   3511: strings naming the response IDs. This may be empty.
1.187     bowersj2 3512: 
1.51      bowersj2 3513: =back
                   3514: 
                   3515: =cut
                   3516: 
                   3517: sub parts {
                   3518:     my $self = shift;
                   3519: 
1.192     bowersj2 3520:     if ($self->ext) { return []; }
1.67      bowersj2 3521: 
1.51      bowersj2 3522:     $self->extractParts();
                   3523:     return $self->{PARTS};
                   3524: }
                   3525: 
                   3526: sub countParts {
                   3527:     my $self = shift;
                   3528:     
                   3529:     my $parts = $self->parts();
1.191     bowersj2 3530: 
                   3531:     # If I left this here, then it's not necessary.
                   3532:     #my $delta = 0;
                   3533:     #for my $part (@$parts) {
                   3534:     #    if ($part eq '0') { $delta--; }
                   3535:     #}
1.66      bowersj2 3536: 
                   3537:     if ($self->{RESOURCE_ERROR}) {
                   3538:         return 0;
                   3539:     }
                   3540: 
1.191     bowersj2 3541:     return scalar(@{$parts}); # + $delta;
1.192     bowersj2 3542: }
                   3543: 
                   3544: sub multipart {
                   3545:     my $self = shift;
                   3546:     return $self->countParts() > 1;
1.51      bowersj2 3547: }
                   3548: 
1.225     bowersj2 3549: sub singlepart {
                   3550:     my $self = shift;
                   3551:     return $self->countParts() == 1;
                   3552: }
                   3553: 
1.187     bowersj2 3554: sub responseType {
1.184     bowersj2 3555:     my $self = shift;
                   3556:     my $part = shift;
                   3557: 
                   3558:     $self->extractParts();
1.235     albertel 3559:     if (defined($self->{RESPONSE_TYPES}->{$part})) {
                   3560: 	return @{$self->{RESPONSE_TYPES}->{$part}};
                   3561:     } else {
                   3562: 	return undef;
                   3563:     }
1.187     bowersj2 3564: }
                   3565: 
1.193     bowersj2 3566: sub responseIds {
1.187     bowersj2 3567:     my $self = shift;
                   3568:     my $part = shift;
                   3569: 
                   3570:     $self->extractParts();
1.235     albertel 3571:     if (defined($self->{RESPONSE_IDS}->{$part})) {
                   3572: 	return @{$self->{RESPONSE_IDS}->{$part}};
                   3573:     } else {
                   3574: 	return undef;
                   3575:     }
1.184     bowersj2 3576: }
                   3577: 
                   3578: # Private function: Extracts the parts information, both part names and
1.187     bowersj2 3579: # part types, and saves it. 
1.51      bowersj2 3580: sub extractParts { 
                   3581:     my $self = shift;
                   3582:     
1.153     bowersj2 3583:     return if (defined($self->{PARTS}));
1.67      bowersj2 3584:     return if ($self->ext);
1.51      bowersj2 3585: 
                   3586:     $self->{PARTS} = [];
                   3587: 
1.181     bowersj2 3588:     my %parts;
                   3589: 
1.82      bowersj2 3590:     # Retrieve part count, if this is a problem
                   3591:     if ($self->is_problem()) {
1.240     albertel 3592: 	my $partorder = &Apache::lonnet::metadata($self->src(), 'partorder');
1.152     matthew  3593:         my $metadata = &Apache::lonnet::metadata($self->src(), 'packages');
1.181     bowersj2 3594: 
1.239     bowersj2 3595: 	if ($partorder) {
                   3596: 	    my @parts;
                   3597: 	    for my $part (split (/,/,$partorder)) {
                   3598: 		if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
                   3599: 		    push @parts, $part;
1.241     albertel 3600: 		    $parts{$part} = 1;
1.239     bowersj2 3601: 		}
                   3602: 	    }
                   3603: 	    $self->{PARTS} = \@parts;
                   3604: 	} else {
                   3605: 	    if (!$metadata) {
                   3606: 		$self->{RESOURCE_ERROR} = 1;
                   3607: 		$self->{PARTS} = [];
                   3608: 		$self->{PART_TYPE} = {};
                   3609: 		return;
                   3610: 	    }
                   3611: 	    foreach (split(/\,/,$metadata)) {
                   3612: 		if ($_ =~ /^part_(.*)$/) {
                   3613: 		    my $part = $1;
                   3614: 		    # This floods the logs if it blows up
                   3615: 		    if (defined($parts{$part})) {
1.241     albertel 3616: 			&Apache::lonnet::logthis("$part multiply defined in metadata for " . $self->symb());
                   3617: 		    }
1.239     bowersj2 3618: 		    
                   3619: 		    # check to see if part is turned off.
                   3620: 		    
                   3621: 		    if (!Apache::loncommon::check_if_partid_hidden($part, $self->symb())) {
                   3622: 			$parts{$part} = 1;
                   3623: 		    }
                   3624: 		}
                   3625: 	    }
                   3626: 	    my @sortedParts = sort keys %parts;
                   3627: 	    $self->{PARTS} = \@sortedParts;
1.51      bowersj2 3628:         }
1.82      bowersj2 3629:         
1.187     bowersj2 3630: 
                   3631:         my %responseIdHash;
                   3632:         my %responseTypeHash;
                   3633: 
1.189     bowersj2 3634: 
                   3635:         # Init the responseIdHash
                   3636:         foreach (@{$self->{PARTS}}) {
                   3637:             $responseIdHash{$_} = [];
                   3638:         }
                   3639: 
1.187     bowersj2 3640:         # Now, the unfortunate thing about this is that parts, part name, and
1.239     bowersj2 3641:         # response id are delimited by underscores, but both the part
1.187     bowersj2 3642:         # name and response id can themselves have underscores in them.
                   3643:         # So we have to use our knowlege of part names to figure out 
                   3644:         # where the part names begin and end, and even then, it is possible
                   3645:         # to construct ambiguous situations.
                   3646:         foreach (split /,/, $metadata) {
                   3647:             if ($_ =~ /^([a-zA-Z]+)response_(.*)/) {
                   3648:                 my $responseType = $1;
                   3649:                 my $partStuff = $2;
                   3650:                 my $partIdSoFar = '';
                   3651:                 my @partChunks = split /_/, $partStuff;
                   3652:                 my $i = 0;
                   3653:                 for ($i = 0; $i < scalar(@partChunks); $i++) {
                   3654:                     if ($partIdSoFar) { $partIdSoFar .= '_'; }
                   3655:                     $partIdSoFar .= $partChunks[$i];
                   3656:                     if ($parts{$partIdSoFar}) {
                   3657:                         my @otherChunks = @partChunks[$i+1..$#partChunks];
                   3658:                         my $responseId = join('_', @otherChunks);
1.188     bowersj2 3659:                         push @{$responseIdHash{$partIdSoFar}}, $responseId;
1.233     matthew  3660:                         push @{$responseTypeHash{$partIdSoFar}}, $responseType;
1.187     bowersj2 3661:                     }
                   3662:                 }
                   3663:             }
                   3664:         }
                   3665:         $self->{RESPONSE_IDS} = \%responseIdHash;
                   3666:         $self->{RESPONSE_TYPES} = \%responseTypeHash;
1.154     bowersj2 3667:     }
                   3668: 
1.51      bowersj2 3669:     return;
                   3670: }
                   3671: 
                   3672: =pod
                   3673: 
                   3674: =head2 Resource Status
                   3675: 
1.174     albertel 3676: Problem resources have status information, reflecting their various
                   3677: dates and completion statuses.
1.51      bowersj2 3678: 
1.174     albertel 3679: There are two aspects to the status: the date-related information and
                   3680: the completion information.
1.51      bowersj2 3681: 
1.174     albertel 3682: Idiomatic usage of these two methods would probably look something
                   3683: like
1.51      bowersj2 3684: 
                   3685:  foreach ($resource->parts()) {
                   3686:     my $dateStatus = $resource->getDateStatus($_);
                   3687:     my $completionStatus = $resource->getCompletionStatus($_);
                   3688: 
1.70      bowersj2 3689:     or
                   3690: 
                   3691:     my $status = $resource->status($_);
                   3692: 
1.51      bowersj2 3693:     ... use it here ...
                   3694:  }
                   3695: 
1.174     albertel 3696: Which you use depends on exactly what you are looking for. The
                   3697: status() function has been optimized for the nav maps display and may
                   3698: not precisely match what you need elsewhere.
1.101     bowersj2 3699: 
1.174     albertel 3700: The symbolic constants shown below can be accessed through the
                   3701: resource object: C<$res->OPEN>.
1.101     bowersj2 3702: 
1.51      bowersj2 3703: =over 4
                   3704: 
1.174     albertel 3705: =item * B<getDateStatus>($part):
                   3706: 
                   3707: ($part defaults to 0). A convenience function that returns a symbolic
                   3708: constant telling you about the date status of the part. The possible
                   3709: return values are:
1.51      bowersj2 3710: 
                   3711: =back
                   3712: 
                   3713: B<Date Codes>
                   3714: 
                   3715: =over 4
                   3716: 
1.174     albertel 3717: =item * B<OPEN_LATER>:
                   3718: 
                   3719: The problem will be opened later.
                   3720: 
                   3721: =item * B<OPEN>:
                   3722: 
                   3723: Open and not yet due.
                   3724: 
1.51      bowersj2 3725: 
1.174     albertel 3726: =item * B<PAST_DUE_ANSWER_LATER>:
1.51      bowersj2 3727: 
1.174     albertel 3728: The due date has passed, but the answer date has not yet arrived.
1.59      bowersj2 3729: 
1.174     albertel 3730: =item * B<PAST_DUE_NO_ANSWER>:
1.54      bowersj2 3731: 
1.174     albertel 3732: The due date has passed and there is no answer opening date set.
1.51      bowersj2 3733: 
1.174     albertel 3734: =item * B<ANSWER_OPEN>:
1.51      bowersj2 3735: 
1.174     albertel 3736: The answer date is here.
                   3737: 
                   3738: =item * B<NETWORK_FAILURE>:
                   3739: 
                   3740: The information is unknown due to network failure.
1.51      bowersj2 3741: 
                   3742: =back
                   3743: 
                   3744: =cut
                   3745: 
                   3746: # Apparently the compiler optimizes these into constants automatically
1.54      bowersj2 3747: sub OPEN_LATER             { return 0; }
                   3748: sub OPEN                   { return 1; }
                   3749: sub PAST_DUE_NO_ANSWER     { return 2; }
                   3750: sub PAST_DUE_ANSWER_LATER  { return 3; }
                   3751: sub ANSWER_OPEN            { return 4; }
                   3752: sub NOTHING_SET            { return 5; } 
                   3753: sub NETWORK_FAILURE        { return 100; }
                   3754: 
                   3755: # getDateStatus gets the date status for a given problem part. 
                   3756: # Because answer date, due date, and open date are fully independent
                   3757: # (i.e., it is perfectly possible to *only* have an answer date), 
                   3758: # we have to completely cover the 3x3 maxtrix of (answer, due, open) x
                   3759: # (past, future, none given). This function handles this with a decision
                   3760: # tree. Read the comments to follow the decision tree.
1.51      bowersj2 3761: 
                   3762: sub getDateStatus {
                   3763:     my $self = shift;
                   3764:     my $part = shift;
                   3765:     $part = "0" if (!defined($part));
1.54      bowersj2 3766: 
                   3767:     # Always return network failure if there was one.
1.51      bowersj2 3768:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3769: 
                   3770:     my $now = time();
                   3771: 
1.53      bowersj2 3772:     my $open = $self->opendate($part);
                   3773:     my $due = $self->duedate($part);
                   3774:     my $answer = $self->answerdate($part);
                   3775: 
                   3776:     if (!$open && !$due && !$answer) {
                   3777:         # no data on the problem at all
                   3778:         # should this be the same as "open later"? think multipart.
                   3779:         return $self->NOTHING_SET;
                   3780:     }
1.59      bowersj2 3781:     if (!$open || $now < $open) {return $self->OPEN_LATER}
                   3782:     if (!$due || $now < $due) {return $self->OPEN}
                   3783:     if ($answer && $now < $answer) {return $self->PAST_DUE_ANSWER_LATER}
                   3784:     if ($answer) { return $self->ANSWER_OPEN; }
1.54      bowersj2 3785:     return PAST_DUE_NO_ANSWER;
1.51      bowersj2 3786: }
                   3787: 
                   3788: =pod
                   3789: 
                   3790: B<>
                   3791: 
                   3792: =over 4
                   3793: 
1.174     albertel 3794: =item * B<getCompletionStatus>($part):
1.51      bowersj2 3795: 
1.174     albertel 3796: ($part defaults to 0.) A convenience function that returns a symbolic
                   3797: constant telling you about the completion status of the part, with the
                   3798: following possible results:
                   3799: 
                   3800: =back
1.51      bowersj2 3801: 
                   3802: B<Completion Codes>
                   3803: 
                   3804: =over 4
                   3805: 
1.174     albertel 3806: =item * B<NOT_ATTEMPTED>:
                   3807: 
                   3808: Has not been attempted at all.
                   3809: 
                   3810: =item * B<INCORRECT>:
                   3811: 
                   3812: Attempted, but wrong by student.
1.51      bowersj2 3813: 
1.174     albertel 3814: =item * B<INCORRECT_BY_OVERRIDE>:
1.51      bowersj2 3815: 
1.174     albertel 3816: Attempted, but wrong by instructor override.
1.51      bowersj2 3817: 
1.174     albertel 3818: =item * B<CORRECT>:
1.51      bowersj2 3819: 
1.174     albertel 3820: Correct or correct by instructor.
1.51      bowersj2 3821: 
1.174     albertel 3822: =item * B<CORRECT_BY_OVERRIDE>:
1.51      bowersj2 3823: 
1.174     albertel 3824: Correct by instructor override.
1.51      bowersj2 3825: 
1.174     albertel 3826: =item * B<EXCUSED>:
                   3827: 
                   3828: Excused. Not yet implemented.
                   3829: 
                   3830: =item * B<NETWORK_FAILURE>:
                   3831: 
                   3832: Information not available due to network failure.
                   3833: 
                   3834: =item * B<ATTEMPTED>:
                   3835: 
                   3836: Attempted, and not yet graded.
1.69      bowersj2 3837: 
1.51      bowersj2 3838: =back
                   3839: 
                   3840: =cut
                   3841: 
1.53      bowersj2 3842: sub NOT_ATTEMPTED         { return 10; }
                   3843: sub INCORRECT             { return 11; }
                   3844: sub INCORRECT_BY_OVERRIDE { return 12; }
                   3845: sub CORRECT               { return 13; }
                   3846: sub CORRECT_BY_OVERRIDE   { return 14; }
                   3847: sub EXCUSED               { return 15; }
1.69      bowersj2 3848: sub ATTEMPTED             { return 16; }
1.51      bowersj2 3849: 
                   3850: sub getCompletionStatus {
                   3851:     my $self = shift;
                   3852:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3853: 
1.108     bowersj2 3854:     my $status = $self->queryRestoreHash('solved', shift);
1.51      bowersj2 3855: 
1.251     www      3856:     # Left as separate if statements in case we ever do more with this
1.51      bowersj2 3857:     if ($status eq 'correct_by_student') {return $self->CORRECT;}
                   3858:     if ($status eq 'correct_by_override') {return $self->CORRECT_BY_OVERRIDE; }
                   3859:     if ($status eq 'incorrect_attempted') {return $self->INCORRECT; }
                   3860:     if ($status eq 'incorrect_by_override') {return $self->INCORRECT_BY_OVERRIDE; }
                   3861:     if ($status eq 'excused') {return $self->EXCUSED; }
1.69      bowersj2 3862:     if ($status eq 'ungraded_attempted') {return $self->ATTEMPTED; }
1.51      bowersj2 3863:     return $self->NOT_ATTEMPTED;
1.108     bowersj2 3864: }
                   3865: 
                   3866: sub queryRestoreHash {
                   3867:     my $self = shift;
                   3868:     my $hashentry = shift;
                   3869:     my $part = shift;
1.185     bowersj2 3870:     $part = "0" if (!defined($part) || $part eq '');
1.108     bowersj2 3871:     return $self->NETWORK_FAILURE if ($self->{NAV_MAP}->{NETWORK_FAILURE});
                   3872: 
                   3873:     $self->getReturnHash();
                   3874: 
                   3875:     return $self->{RETURN_HASH}->{'resource.'.$part.'.'.$hashentry};
1.51      bowersj2 3876: }
                   3877: 
                   3878: =pod
                   3879: 
                   3880: B<Composite Status>
                   3881: 
1.174     albertel 3882: Along with directly returning the date or completion status, the
                   3883: resource object includes a convenience function B<status>() that will
                   3884: combine the two status tidbits into one composite status that can
1.191     bowersj2 3885: represent the status of the resource as a whole. This method represents
                   3886: the concept of the thing we want to display to the user on the nav maps
                   3887: screen, which is a combination of completion and open status. The precise logic is
1.174     albertel 3888: documented in the comments of the status method. The following results
                   3889: may be returned, all available as methods on the resource object
1.185     bowersj2 3890: ($res->NETWORK_FAILURE): In addition to the return values that match
                   3891: the date or completion status, this function can return "ANSWER_SUBMITTED"
                   3892: if that problemstatus parameter value is set to No, suppressing the
                   3893: incorrect/correct feedback.
1.51      bowersj2 3894: 
                   3895: =over 4
                   3896: 
1.174     albertel 3897: =item * B<NETWORK_FAILURE>:
                   3898: 
                   3899: The network has failed and the information is not available.
1.51      bowersj2 3900: 
1.174     albertel 3901: =item * B<NOTHING_SET>:
1.53      bowersj2 3902: 
1.174     albertel 3903: No dates have been set for this problem (part) at all. (Because only
                   3904: certain parts of a multi-part problem may be assigned, this can not be
                   3905: collapsed into "open later", as we do not know a given part will EVER
                   3906: be opened. For single part, this is the same as "OPEN_LATER".)
1.51      bowersj2 3907: 
1.174     albertel 3908: =item * B<CORRECT>:
1.51      bowersj2 3909: 
1.174     albertel 3910: For any reason at all, the part is considered correct.
1.54      bowersj2 3911: 
1.174     albertel 3912: =item * B<EXCUSED>:
1.51      bowersj2 3913: 
1.174     albertel 3914: For any reason at all, the problem is excused.
1.51      bowersj2 3915: 
1.174     albertel 3916: =item * B<PAST_DUE_NO_ANSWER>:
1.51      bowersj2 3917: 
1.174     albertel 3918: The problem is past due, not considered correct, and no answer date is
                   3919: set.
1.51      bowersj2 3920: 
1.174     albertel 3921: =item * B<PAST_DUE_ANSWER_LATER>:
1.51      bowersj2 3922: 
1.174     albertel 3923: The problem is past due, not considered correct, and an answer date in
                   3924: the future is set.
1.51      bowersj2 3925: 
1.174     albertel 3926: =item * B<ANSWER_OPEN>:
                   3927: 
                   3928: The problem is past due, not correct, and the answer is now available.
                   3929: 
                   3930: =item * B<OPEN_LATER>:
                   3931: 
                   3932: The problem is not yet open.
                   3933: 
                   3934: =item * B<TRIES_LEFT>:
                   3935: 
                   3936: The problem is open, has been tried, is not correct, but there are
                   3937: tries left.
                   3938: 
                   3939: =item * B<INCORRECT>:
                   3940: 
                   3941: The problem is open, and all tries have been used without getting the
                   3942: correct answer.
                   3943: 
                   3944: =item * B<OPEN>:
                   3945: 
                   3946: The item is open and not yet tried.
                   3947: 
                   3948: =item * B<ATTEMPTED>:
                   3949: 
                   3950: The problem has been attempted.
1.69      bowersj2 3951: 
1.185     bowersj2 3952: =item * B<ANSWER_SUBMITTED>:
                   3953: 
                   3954: An answer has been submitted, but the student should not see it.
                   3955: 
1.51      bowersj2 3956: =back
                   3957: 
                   3958: =cut
                   3959: 
1.185     bowersj2 3960: sub TRIES_LEFT       { return 20; }
                   3961: sub ANSWER_SUBMITTED { return 21; }
1.51      bowersj2 3962: 
                   3963: sub status {
                   3964:     my $self = shift;
                   3965:     my $part = shift;
                   3966:     if (!defined($part)) { $part = "0"; }
                   3967:     my $completionStatus = $self->getCompletionStatus($part);
                   3968:     my $dateStatus = $self->getDateStatus($part);
                   3969: 
                   3970:     # What we have is a two-dimensional matrix with 4 entries on one
                   3971:     # dimension and 5 entries on the other, which we want to colorize,
1.54      bowersj2 3972:     # plus network failure and "no date data at all".
1.51      bowersj2 3973: 
1.222     bowersj2 3974:     #if ($self->{RESOURCE_ERROR}) { return NETWORK_FAILURE; }
1.53      bowersj2 3975:     if ($completionStatus == NETWORK_FAILURE) { return NETWORK_FAILURE; }
1.51      bowersj2 3976: 
1.236     bowersj2 3977:     my $suppressFeedback = $self->problemstatus($part) eq 'no';
                   3978:     # If there's an answer date and we're past it, don't
                   3979:     # suppress the feedback; student should know
                   3980:     if ($self->answerdate($part) && $self->answerdate($part) < time()) {
                   3981: 	$suppressFeedback = 0;
                   3982:     }
1.185     bowersj2 3983: 
1.51      bowersj2 3984:     # There are a few whole rows we can dispose of:
1.53      bowersj2 3985:     if ($completionStatus == CORRECT ||
                   3986:         $completionStatus == CORRECT_BY_OVERRIDE ) {
1.185     bowersj2 3987:         return $suppressFeedback? ANSWER_SUBMITTED : CORRECT; 
1.69      bowersj2 3988:     }
                   3989: 
                   3990:     if ($completionStatus == ATTEMPTED) {
                   3991:         return ATTEMPTED;
1.53      bowersj2 3992:     }
                   3993: 
                   3994:     # If it's EXCUSED, then return that no matter what
                   3995:     if ($completionStatus == EXCUSED) {
                   3996:         return EXCUSED; 
1.51      bowersj2 3997:     }
                   3998: 
1.53      bowersj2 3999:     if ($dateStatus == NOTHING_SET) {
                   4000:         return NOTHING_SET;
1.51      bowersj2 4001:     }
                   4002: 
1.69      bowersj2 4003:     # Now we're down to a 4 (incorrect, incorrect_override, not_attempted)
                   4004:     # by 4 matrix (date statuses).
1.51      bowersj2 4005: 
1.54      bowersj2 4006:     if ($dateStatus == PAST_DUE_ANSWER_LATER ||
1.59      bowersj2 4007:         $dateStatus == PAST_DUE_NO_ANSWER ) {
1.54      bowersj2 4008:         return $dateStatus; 
1.51      bowersj2 4009:     }
                   4010: 
1.53      bowersj2 4011:     if ($dateStatus == ANSWER_OPEN) {
                   4012:         return ANSWER_OPEN;
1.51      bowersj2 4013:     }
                   4014: 
                   4015:     # Now: (incorrect, incorrect_override, not_attempted) x 
                   4016:     # (open_later), (open)
                   4017:     
1.53      bowersj2 4018:     if ($dateStatus == OPEN_LATER) {
                   4019:         return OPEN_LATER;
1.51      bowersj2 4020:     }
                   4021: 
                   4022:     # If it's WRONG...
1.53      bowersj2 4023:     if ($completionStatus == INCORRECT || $completionStatus == INCORRECT_BY_OVERRIDE) {
1.51      bowersj2 4024:         # and there are TRIES LEFT:
1.79      bowersj2 4025:         if ($self->tries($part) < $self->maxtries($part) || !$self->maxtries($part)) {
1.222     bowersj2 4026:             return $suppressFeedback ? ANSWER_SUBMITTED : TRIES_LEFT;
1.51      bowersj2 4027:         }
1.185     bowersj2 4028:         return $suppressFeedback ? ANSWER_SUBMITTED : INCORRECT; # otherwise, return orange; student can't fix this
1.51      bowersj2 4029:     }
                   4030: 
                   4031:     # Otherwise, it's untried and open
1.53      bowersj2 4032:     return OPEN; 
1.224     bowersj2 4033: }
                   4034: 
                   4035: sub CLOSED { return 23; }
                   4036: sub ERROR { return 24; }
                   4037: 
                   4038: =pod
                   4039: 
                   4040: B<Simple Status>
                   4041: 
                   4042: Convenience method B<simpleStatus> provides a "simple status" for the resource.
                   4043: "Simple status" corresponds to "which icon is shown on the
                   4044: Navmaps". There are six "simple" statuses:
                   4045: 
                   4046: =over 4
                   4047: 
                   4048: =item * B<CLOSED>: The problem is currently closed. (No icon shown.)
                   4049: 
                   4050: =item * B<OPEN>: The problem is open and unattempted.
                   4051: 
                   4052: =item * B<CORRECT>: The problem is correct for any reason.
                   4053: 
                   4054: =item * B<INCORRECT>: The problem is incorrect and can still be
                   4055: completed successfully.
                   4056: 
                   4057: =item * B<ATTEMPTED>: The problem has been attempted, but the student
                   4058: does not know if they are correct. (The ellipsis icon.)
                   4059: 
                   4060: =item * B<ERROR>: There is an error retrieving information about this
                   4061: problem.
                   4062: 
                   4063: =back
                   4064: 
                   4065: =cut
                   4066: 
                   4067: # This hash maps the composite status to this simple status, and
                   4068: # can be used directly, if you like
                   4069: my %compositeToSimple = 
                   4070:     (
                   4071:       NETWORK_FAILURE()       => ERROR,
                   4072:       NOTHING_SET()           => CLOSED,
                   4073:       CORRECT()               => CORRECT,
                   4074:       EXCUSED()               => CORRECT,
                   4075:       PAST_DUE_NO_ANSWER()    => INCORRECT,
                   4076:       PAST_DUE_ANSWER_LATER() => INCORRECT,
                   4077:       ANSWER_OPEN()           => INCORRECT,
                   4078:       OPEN_LATER()            => CLOSED,
                   4079:       TRIES_LEFT()            => OPEN,
                   4080:       INCORRECT()             => INCORRECT,
                   4081:       OPEN()                  => OPEN,
                   4082:       ATTEMPTED()             => ATTEMPTED,
                   4083:       ANSWER_SUBMITTED()      => ATTEMPTED
                   4084:      );
                   4085: 
                   4086: sub simpleStatus {
                   4087:     my $self = shift;
                   4088:     my $part = shift;
                   4089:     my $status = $self->status($part);
                   4090:     return $compositeToSimple{$status};
1.225     bowersj2 4091: }
                   4092: 
                   4093: =pod
                   4094: 
                   4095: B<simpleStatusCount> will return an array reference containing, in
                   4096: this order, the number of OPEN, CLOSED, CORRECT, INCORRECT, ATTEMPTED,
                   4097: and ERROR parts the given problem has.
                   4098: 
                   4099: =cut
                   4100:     
                   4101: # This maps the status to the slot we want to increment
                   4102: my %statusToSlotMap = 
                   4103:     (
                   4104:      OPEN()      => 0,
                   4105:      CLOSED()    => 1,
                   4106:      CORRECT()   => 2,
                   4107:      INCORRECT() => 3,
                   4108:      ATTEMPTED() => 4,
                   4109:      ERROR()     => 5
                   4110:      );
                   4111: 
                   4112: sub statusToSlot { return $statusToSlotMap{shift()}; }
                   4113: 
                   4114: sub simpleStatusCount {
                   4115:     my $self = shift;
                   4116: 
                   4117:     my @counts = (0, 0, 0, 0, 0, 0, 0);
                   4118:     foreach my $part (@{$self->parts()}) {
                   4119: 	$counts[$statusToSlotMap{$self->simpleStatus($part)}]++;
                   4120:     }
                   4121: 
                   4122:     return \@counts;
1.191     bowersj2 4123: }
                   4124: 
                   4125: =pod
                   4126: 
                   4127: B<Completable>
                   4128: 
                   4129: The completable method represents the concept of I<whether the student can
                   4130: currently do the problem>. If the student can do the problem, which means
                   4131: that it is open, there are tries left, and if the problem is manually graded
                   4132: or the grade is suppressed via problemstatus, the student has not tried it
                   4133: yet, then the method returns 1. Otherwise, it returns 0, to indicate that 
                   4134: either the student has tried it and there is no feedback, or that for
                   4135: some reason it is no longer completable (not open yet, successfully completed,
                   4136: out of tries, etc.). As an example, this is used as the filter for the
                   4137: "Uncompleted Homework" option for the nav maps.
                   4138: 
                   4139: If this does not quite meet your needs, do not fiddle with it (unless you are
                   4140: fixing it to better match the student's conception of "completable" because
                   4141: it's broken somehow)... make a new method.
                   4142: 
                   4143: =cut
                   4144: 
                   4145: sub completable {
                   4146:     my $self = shift;
                   4147:     if (!$self->is_problem()) { return 0; }
                   4148:     my $partCount = $self->countParts();
                   4149: 
                   4150:     foreach my $part (@{$self->parts()}) {
                   4151:         if ($part eq '0' && $partCount != 1) { next; }
                   4152:         my $status = $self->status($part);
                   4153:         # "If any of the parts are open, or have tries left (implies open),
                   4154:         # and it is not "attempted" (manually graded problem), it is
                   4155:         # not "complete"
1.216     bowersj2 4156: 	if ($self->getCompletionStatus($part) == ATTEMPTED() ||
                   4157: 	    $status == ANSWER_SUBMITTED() ) {
                   4158: 	    # did this part already, as well as we can
                   4159: 	    next;
                   4160: 	}
                   4161: 	if ($status == OPEN() || $status == TRIES_LEFT()) {
                   4162: 	    return 1;
                   4163: 	}
1.191     bowersj2 4164:     }
                   4165:         
                   4166:     # If all the parts were complete, so was this problem.
1.216     bowersj2 4167:     return 0;
1.51      bowersj2 4168: }
                   4169: 
                   4170: =pod
                   4171: 
                   4172: =head2 Resource/Nav Map Navigation
                   4173: 
                   4174: =over 4
                   4175: 
1.174     albertel 4176: =item * B<getNext>():
                   4177: 
                   4178: Retreive an array of the possible next resources after this
                   4179: one. Always returns an array, even in the one- or zero-element case.
                   4180: 
                   4181: =item * B<getPrevious>():
1.85      bowersj2 4182: 
1.174     albertel 4183: Retreive an array of the possible previous resources from this
                   4184: one. Always returns an array, even in the one- or zero-element case.
1.51      bowersj2 4185: 
                   4186: =cut
                   4187: 
                   4188: sub getNext {
                   4189:     my $self = shift;
                   4190:     my @branches;
                   4191:     my $to = $self->to();
1.85      bowersj2 4192:     foreach my $branch ( split(/,/, $to) ) {
1.51      bowersj2 4193:         my $choice = $self->{NAV_MAP}->getById($branch);
                   4194:         my $next = $choice->goesto();
                   4195:         $next = $self->{NAV_MAP}->getById($next);
                   4196: 
1.131     bowersj2 4197:         push @branches, $next;
1.85      bowersj2 4198:     }
                   4199:     return \@branches;
                   4200: }
                   4201: 
                   4202: sub getPrevious {
                   4203:     my $self = shift;
                   4204:     my @branches;
                   4205:     my $from = $self->from();
                   4206:     foreach my $branch ( split /,/, $from) {
                   4207:         my $choice = $self->{NAV_MAP}->getById($branch);
                   4208:         my $prev = $choice->comesfrom();
                   4209:         $prev = $self->{NAV_MAP}->getById($prev);
                   4210: 
1.131     bowersj2 4211:         push @branches, $prev;
1.51      bowersj2 4212:     }
                   4213:     return \@branches;
1.131     bowersj2 4214: }
                   4215: 
                   4216: sub browsePriv {
                   4217:     my $self = shift;
                   4218:     if (defined($self->{BROWSE_PRIV})) {
                   4219:         return $self->{BROWSE_PRIV};
                   4220:     }
                   4221: 
                   4222:     $self->{BROWSE_PRIV} = &Apache::lonnet::allowed('bre', $self->src());
1.51      bowersj2 4223: }
                   4224: 
                   4225: =pod
1.2       www      4226: 
1.51      bowersj2 4227: =back
1.2       www      4228: 
1.51      bowersj2 4229: =cut
1.2       www      4230: 
1.51      bowersj2 4231: 1;
1.2       www      4232: 
1.51      bowersj2 4233: __END__
1.2       www      4234: 
                   4235: 

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