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

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

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