File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.280: download - view: text, annotated - select for diffs
Fri Aug 27 20:34:13 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- in inline mode when you close the window using the close link, need to update the main window to let itknow I am going away

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

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