File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.338: download - view: text, annotated - select for diffs
Fri Sep 23 21:30:25 2005 UTC (18 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- remove some debugging spew

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

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