File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.345: download - view: text, annotated - select for diffs
Sun Oct 30 02:31:01 2005 UTC (18 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
"Here" marker looks a lot better when symmetric

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.