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

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

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