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

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

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