File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.270: download - view: text, annotated - select for diffs
Fri Jul 23 22:38:10 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- okay you can now 'sort' the navmaps display by title or duedate
    in the title case it doesn't show any maps
    in the duedate case it only shows homeworks (right now, will do contentclose soonish)
- bugs,
   - need to also do by 'type' then by title
   - links for resource in pages are wrong

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

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