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

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

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