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

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

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