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

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

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