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

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

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