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

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

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