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

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

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