File:  [LON-CAPA] / loncom / interface / lonnavmaps.pm
Revision 1.278: download - view: text, annotated - select for diffs
Mon Aug 23 21:05:03 2004 UTC (19 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- inline remote with external navmap works well now

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

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