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

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

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