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

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

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