File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.300: download - view: text, annotated - select for diffs
Thu Oct 7 22:12:47 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixes bug#3350 hopefully for good.
    - $navmaps objects never actaully got cleaned up due the resource objects in it holding a reference back to the navmap object, this meant the hashes didn't get untied and that we leaked memory
    - needs WeakRef

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

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