Annotation of loncom/interface/lonnavmaps.pm, revision 1.316

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

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