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

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

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