File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.277: download - view: text, annotated - select for diffs
Fri Aug 20 20:14:27 2004 UTC (19 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
avoid internal server error when get by symb fails to find resource.

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

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