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

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

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