File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.316: download - view: text, annotated - select for diffs
Thu Feb 17 08:29:43 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- <html> -> &Apache::lonxml::xmlbegin, thus valid doctypes are now getting output, Yeah! StandardsCmpliance

- backing out the encoding changes for now

- some xhtml cleanups
- one icon -> lonhttpd

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

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