File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.274: download - view: text, annotated - select for diffs
Tue Aug 10 20:52:03 2004 UTC (19 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added part_display method to resource object.  Modified navmaps page to use
this method.

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

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